Task Scheduler

Purpose

The Task Scheduler allows you to perform automated tasks on a chosen computer. The Task Scheduler monitors whatever criteria you choose and executes the task when the criteria for executing the task have been met. For example, you can have the computer run ScanDisk at 7:00 P.M. every Sunday.

About the Task Scheduler

General information about the Task Scheduler API.

Using the Task Scheduler

Code examples that show how to use the Task Scheduler API.

Task Scheduler Reference

Documentation of Task Scheduler API's interfaces, structures, unions, and enumerated types.

Feedback

Make error reports and feature requests directly to Microsoft.

Microsoft Platform SDK, February 2001 Edition.
This content last built on Thursday, February 01, 2001.


About The Task Scheduler

The Task Scheduler service allows you to perform automated tasks on a chosen computer. With this service you can schedule any batch file, program, or document to run at a time that is convenient for you or when a specific event occurs. Task Scheduler monitors the time or event criteria you choose and then executes the task when those criteria are met.

Task Scheduler is automatically installed with the Microsoft® Windows® 2000 operating system and is started each time the operating system is started. It can be run from Windows 2000 (by means of the Task Scheduler graphical user interface) or through the Task Scheduler API, described in this SDK.

Note For information on using Task Scheduler from the Windows 2000, click Start on your Windows 2000 desktop, point to Settings, click Control Panel, and then double-click Scheduled Tasks. On the Help menu, click Help Topics.

With the Task Scheduler API you can:

  • Create work items (currently the only work item available are tasks).
  • Schedule a task to run at a specific time or when a specific event occurs.
  • Change the schedule for a task.
  • Customize how tasks run.
  • Stop a scheduled task.


The Task Scheduler API

The Task Scheduler API consist of several COM objects and their associated interfaces. The following illustration shows a task scheduler object, which represents the Task Scheduler service; an enumeration object and task object, which are created by ITaskScheduler method calls; and a task trigger object, which is created by IScheduledWorkItem method calls. Note that the IScheduledWorkItem methods are inherited by the ITask interface.

Note Task Scheduler uses two standard COM interfaces: IUnknown and IPersistFile.

The IUnknown interface is supported by all Task Scheduler objects, and all Task Scheduler interfaces inherit its methods. It is used to retrieve pointers to other interfaces on a given object. These pointers are retrieved through calls to IUnknown::QueryInterface.

The IPersistFile interface (supported by the task object) is used to save a task to disk. Whenever you create a new task object or modify an existing task object, you must call IPersistFile::Save to store the task to disk.


Programming Considerations

When developing applications that use the Task Scheduler API, keep the following programming issues in mind.

  • Your application must make sure the Task Scheduler service is running before attempting to make any calls using the Task Schedular API.
  • When retrieving strings, make sure you call CoTaskMemFree to release each string after it is no longer needed. When retrieving arrays of strings, make sure you first release each string in the array and then release the array iteself.
  • When creating or modifying a work item, including triggers associated with a work item, make sure you call IPersistFile::Save to save the work item to disk.
  • After using any of the interfaces provided by the Task Scheduler API, make sure you call IUnknown::Release to release the interface. IUnknown is supported by each Task Scheduler object.

The Using section of the Task Scheduler documentation provides numerous examples that follow these guidelines. The table below provides jumps to some of these examples.

For an example of | See
Starting the Task Scheduler service | Starting the Task Scheduler Service
Releasing strings | Retrieving Work Item Property Examples
Saving work items to disk | Setting Work Item Property Examples
Releasing interfaces | Creating a Task Using NewWorkItem Example


Scheduled Work Items

Task Scheduler uses two terms to describe what it can schedule: work items and tasks. Of these, work item is a more general term that describes any type of item that can be scheduled. It can be any item that the Task Scheduler service runs at a time specified by the item's trigger(s).

In contrast, a task is a specific type of work item. Currently, the only type of scheduled work item that is supported is a task.

The IScheduledWorkItem interface contains methods that are supported by all types of scheduled work items. For example, account information, run times, and application-defined comments are properties that may apply to all types of work items. These properties can be set and retrieved through the IScheduledWorkItem interface.

The ITask interface contains methods that are supported by only tasks.

The methods of the IScheduledWorkItem interface are currently inherited by the ITask interface and in the future will be inherited by other work item interfaces.

For examples of | See
Creating a new task. | Creating a Task Using NewWorkItem Example
Running an existing task. | Starting a Task Example
Retrieving properties that apply to all types of work items. | Retrieving Work Item Property Examples
Setting properties that apply to all types of work items. | Setting Work Item Property Examples


Adding Work Items

There are two ways to add work items to the Scheduled Tasks folder. You can create a new work item within the folder, or you can add an existing work item to the folder.

Note Currently only task objects can be added to the Scheduled Tasks folder. When adding a task, you will need to know the identifiers for the task class and the task interface ITask.

You create new work items by calling ITaskScheduler::NewWorkItem. This method creates a new work item object using the name you provide and adds the work item to the Scheduled Tasks folder. When you create a new item, Task Scheduler allocates the memory needed for the new object automatically.

You add existing work items to the Scheduled Tasks folder by calling ITaskScheduler::AddWorkItem. When you call this method, it is your responsibility to create the object.

The names you supply for work items must be unique within the Scheduled Tasks folder. If a work item with the same name already exists when you call ITaskScheduler::NewWorkItem or ITaskScheduler::AddWorkItem, the method returns an ERROR_FILE_EXISTS error.

For an example of | See
Creating a new task | Creating a Task Using NewWorkItem Example


Managing Work Items

Platform SDK: Task Scheduler

Manipulating Work Items

The IScheduledWorkItem interface provides methods for retrieving and setting work item properties; creating, retrieving, and deleting triggers for work items (setting the trigger must be done with the ITaskTrigger::SetTrigger method); and for running, terminating, and deleting the work item.

Note For properties of a specific type of work item, refer to the interface for that type of object. For example, you cannot set the priority level of a work item; however you can use the methods of the ITask interface to retrieve and set the priority of a task.

Whenever you are modifying a work item, you must call IPersistFile::Save to save the modified work item to disk. The IPersistFile interface is a standard COM interface supported by the ITask interface.

For examples of | See
Retrieving properties that apply to all types of work items | Retrieving Work Item Property Examples
Setting properties that apply to all types of work items | Setting Work Item Property Examples
Running a known task | Starting a Task Example
Terminating a running task | Terminating a Task Example
Creating a new trigger for a known task | Creating a New Trigger
Creating an event-based idle trigger for a known task | Creating an Idle Trigger Example
Retrieving the trigger string of all triggers associated with a known task | Retrieving Trigger Strings Example


Tasks

A task is any application or file type that the Task Scheduler can execute. These may include any of the following (as supported by the operating system on which the task will execute): Win32® applications, Win16 applications, OS/2 applications, MS-DOS® applications, batch files (*.bat), command files (*.cmd), or any properly registered file type.

The information that describes a task is kept in a task file that is stored in the Scheduled Tasks folder. The name of these task files include the name of the task, followed by a .job file extension.

For information on | See
Adding tasks | Adding Work Items
Enumerating the tasks in the Scheduled Tasks folder | Enumerating Tasks


Enumerating Tasks

Task Scheduler provides an enumeration object for enumerating the tasks in the Scheduled Tasks folder. The IEnumWorkItems interface of this object provides methods for enumerating the tasks in the folder, resetting the enumeration sequence to the start of the list, skipping tasks, and making a copy of the current enumeration object for later use.

For information on | See
Enumerating the tasks in the Scheduled tasks folder | IEnumWorkItems::Next
Resetting the enumeration to the start of the list | IEnumWorkItems::Reset
Skipping tasks | IEnumWorkItems::Skip
Making a copy of the current enumeration object | IEnumWorkItems::Clone

For an example of | See
Enumerating the tasks in the Scheduled Tasks folder | Enumerating Tasks Example


Converting Task Names to ANSI Characters

Task names are always given in wide characters, so you need to convert the string to ANSI characters if your application is not built for Unicode. Use a function similar to the example below to convert the wide character strings used by Task Scheduler to ANSI characters.

Note Task names are also the name of the files that contains the task information. These files are located in the Tasks folder.

BOOL ConvertString(LPTSTR pszOut, LPWSTR pwszIn, DWORD dwSize)
{
#ifdef UNICODE
    if(lstrcpyn(pszOut, pwszIn, dwSize))
        {
        return TRUE;
        }
#else
    if(WideCharToMultiByte( CP_ACP,
            0,
            pwszIn,
            -1,
            pszOut,
            dwSize,
            NULL,
            NULL))
        {
        return TRUE;
        }
#endif   // UNICODE

return FALSE;
}


Triggers

A trigger is a set of criteria that, when met, will cause a task to be executed. Task Scheduler provides time-based and event-based triggers that can specify task start times, repetition criteria, and other parameters.

Time-based triggers are fired at a specified time. Not only can you set the time of day that they fire, you can also set how often they fire: once, daily, weekly, monthly, on a specified day of the month (for example, the third day of the month), or on a specified day of the week of a month (for example, the second Tuesday of the month).

Event-based triggers are fired in response to certain system events. Event-based triggers can be set to fire when the system starts up, when a user logs on to the local computer, or when the system becomes idle. The last of these is known as an idle trigger.

Each task can have a single trigger associated with it or multiple triggers. Multiple triggers can be thought of as a schedule, a set of times at which something happens. In this case, the schedule is the set of times (specified by the union of all the triggers associated with the work item) at which a work item will execute.


Trigger Interfaces

Applications can use the methods available from the Task Scheduler interfaces to create, retrieve, modify, and delete the triggers for a work item.

The two interfaces used to do this are shown in the following illustration. The IScheduledWorkItem interface is used to manage all the triggers associated with a work item (such management includes creating a new trigger for the work item). The ITaskTrigger interface is used to manage a specific trigger.

The IScheduledWorkItem interface provides methods for creating a new trigger for a work item, retrieving the number of triggers associated with a work item, retrieving the trigger structures and strings of triggers associated with the work item, and for deleting triggers.

Once the trigger object is available, you can use the ITaskTrigger interface to retrieve the trigger structure and string of the trigger and to set the criteria used to fire the trigger. This interface is used only when you are working with a task trigger object.


Trigger Structures

Several structures define the criteria of a trigger.

The following illustration shows the TASK_TRIGGER structure. It has three required members (wBeginYear, wBeginMonth, and wBeginDay) that must be set when creating a new trigger. (To jump to reference page for this structure, click on the structure name in the illustration.)

Note that the TriggerType member uses the TASK_TRIGGER_TYPE enumeration and the Type member uses a TASK_TRIGGER_UNION structure. The TASK_TRIGGER_TYPE enumeration is used to specify the type of trigger (event and time-based trigger types). The TRIGGER_TYPE_UNION structure is used to combine the DAILY, WEEKLY, MONTHLYDATE (day of month), and MONTHLYDOW (day of week) structures used to specify when a time-based trigger will fire.

If TriggerType specifies an only-once time-based trigger or an event-based trigger, the Type member is ignored. The TRIGGER_TYPE_UNION structure is used only if the TriggerType member specifies a daily, weekly, day-of-month, or monthly day-of-week time-based trigger.

In addition, the setting of the Type member indicates which member of the TRIGGER_TYPE_UNION structure is used. The following illustration shows the relationship between the values of the TASK_TRIGGER_TYPE enumeration and the members of the TRIGGER_TYPE_STRUCTURE. (To jump to the reference pages for these structures click on the structure name in the illustration.)


Idle Triggers

An idle trigger is an event-based trigger that is fired a specific amount of time after the computer becomes idle. The computer is considered to be in an idle state when no keyboard or mouse input occurs.

Idle triggers are created by specifying TASK_EVENT_TRIGGER_ON_IDLE in the TASK_TRIGGER_TYPE member of the TASK_TRIGGER structure. The idle trigger is fired when the system becomes idle for the amount of time specified by the idle wait time of the work item.

Note When TASK_EVENT_TRIGGER_ON_IDLE is specified, the wStartHour, wStartMinute, and Type members of the TASK_TRIGGER structure are ignored.

You can set the idle wait time of a work item by calling the IScheduledWorkItem::SetIdleWait method. This method sets the amount of time (in minutes) that the system must remain idle before the trigger is fired and the work item is executed.

To retrieve the idle time of a task, call IScheduledWorkItem::GetIdleWait.


Using the Task Scheduler

This section contains code examples that illustrate how the Task Scheduler API is used. Most of these examples are stand-alone code that can be run by itself, or pasted into a larger application and modified to fit that application's needs.

The following examples are included in this section.

Example | Description
Starting the Task Scheduler Service | Checks what operating system is being used, then starts the Task Scheduler service if it is not running.
Creating a Task Using NewWorkItem Example | Creates a new task.
Enumerating Tasks Example | Enumerates all the tasks on the local computer.
Starting a Task Example | Starts a known task.
Editing a Work Item using Property Pages | Displays the property pages of a task for editing.
Retrieving Work Item Property Examples | A set of examples that show how to retrieve properties that apply to all types of work items.
Setting Work Item Property Examples | A set of examples that show how to set properties that apply to all types of work items.
Retrieving Task Property Examples | A set of examples that show how to retrieve properties unique to tasks.
Setting Task Property Examples | A set of examples that show how to set properties unique to tasks.
Retrieving a Task Page Example | Retrieves and displays the general task page of a known task.
Creating a New Trigger | Creates a new trigger for a known task.
Creating an Idle Trigger Example | Creates an event-based idle trigger for a known task.
Retrieving Trigger Strings Example | Retrieves the trigger string of all triggers associated with a known task.


Starting the Task Scheduler Service

The Task Scheduler service is started by default; however, it is your responsibility to determine if Task Scheduler service is running before using the Task Scheduler API. (Some method calls require the service to be running.) You can start the Task Scheduler service if it is not already running.

To start Task Scheduler

  1. Check which operating system is running.
  2. For the running operating system check to see if the Task Scheduler service is running, and then start the service if it is not running. This example checks for Microsoft® Windows® 95 first and Windows 2000 second.
For a code example using | See
C++ | C/C++ Code Example: Starting Task Scheduler


C/C++ Code Example: Starting Task Scheduler

This example tests to see which operating system is being used, then checks to see if the Task Scheduler service is running. It starts the service if it is not already running.

#include <Windows.h>
#include <stdio.h>

#define SCHED_CLASS             TEXT("SAGEWINDOWCLASS")
#define SCHED_TITLE             TEXT("SYSTEM AGENT COM WINDOW")
#define SCHED_SERVICE_APP_NAME  TEXT("mstask.exe")
#define SCHED_SERVICE_NAME      TEXT("Schedule")

int main(int argc, char **argv)
{

  OSVERSIONINFO osver;
  osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

  /////////////////////////////////////////////////////
  // Determine which version of OS you are running.
  ////////////////////////////////////////////////////
  GetVersionEx(&osver);

  if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  {

    //////////////////////////////////////////////////
    // If Windows 95, check to see if Windows 95
    // version of Task Scheduler is running.
    //////////////////////////////////////////////////
    HWND hwnd = FindWindow(SCHED_CLASS, SCHED_TITLE);

    if (hwnd != NULL)
    {
      // It is already running.
      printf("Task Scheduler is already running.\n");
      return 0;
    }

    //  Execute the task scheduler process.
    STARTUPINFO         sui;
    PROCESS_INFORMATION pi;
    ZeroMemory(&sui, sizeof(sui));
    sui.cb = sizeof (STARTUPINFO);
    TCHAR szApp[MAX_PATH];
    LPTSTR pszPath;

    DWORD dwRet = SearchPath(NULL,
                             SCHED_SERVICE_APP_NAME,
                             NULL,
                             MAX_PATH,
                             szApp,
                             &pszPath);

    if (dwRet == 0)
    {
      return GetLastError();
    }

    BOOL fRet = CreateProcess(szApp,
                              NULL,
                              NULL,
                              NULL,
                              FALSE,
                              CREATE_NEW_CONSOLE |                                  CREATE_NEW_PROCESS_GROUP,
                              NULL,
                              NULL,
                              &sui,
                              &pi);

    if (fRet == 0)
    {
      return GetLastError();
    }

    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    return ERROR_SUCCESS;
  }
  else
  {

    //////////////////////////////////////////////////
    // If not Windows 95, check to see if Windows NT
    // version of Task Scheduler is running.
    //////////////////////////////////////////////////

    SC_HANDLE   hSC = NULL;
    SC_HANDLE   hSchSvc = NULL;

    hSC = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
    if (hSC == NULL)
    {
      return GetLastError();
    }

    hSchSvc = OpenService(hSC,
                          SCHED_SERVICE_NAME,
                          SERVICE_START | SERVICE_QUERY_STATUS);

    CloseServiceHandle(hSC);
    if (hSchSvc == NULL)
    {
      return GetLastError();
    }

    SERVICE_STATUS SvcStatus;

    if (QueryServiceStatus(hSchSvc, &SvcStatus) == FALSE)
    {
      CloseServiceHandle(hSchSvc);
      return GetLastError();
    }

    if (SvcStatus.dwCurrentState == SERVICE_RUNNING)
    {
      // The service is already running.
      CloseServiceHandle(hSchSvc);
      printf("Task Scheduler is already running.\n");
      return 0;
    }

    if (StartService(hSchSvc, 0, NULL) == FALSE)
    {
      CloseServiceHandle(hSchSvc);
      printf("Could not start Task Scheduler.\n");
      return GetLastError();
    }

    CloseServiceHandle(hSchSvc);
    printf("Task Scheduler has been started.\n");
    return ERROR_SUCCESS;
  }
}


Creating a Task Using NewWorkItem Example

When creating a task, you will use two Task Scheduler interfaces: ITaskScheduler and ITask. You will need to provide a unique name for the task, the class identifier of the task object, and the interface identifier of ITask. The class identifier and interface identifier are shown in the code example following this topic.

Note You can also create a task by calling ITaskScheduler::AddWorkItem. When you take this route, it is your responsibility to create an instance of the Task object (which supports the ITask interface) and then add the task with the name you supply.

The name you supply for the task must be unique within the Scheduled Tasks folder. If a task with the same name already exists, ITaskScheduler::NewWorkItem returns ERROR_FILE_EXISTS. If you get this return value, you should specify a different name and attempt to create the task again.

To create a new work item task

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (This example assumes that the Task Scheduler service is running.)
  2. Call ITaskScheduler::NewWorkItem to create a new task. (This method returns a pointer to an ITask interface.)
  3. Save the new task to disk by calling IPersistFile::Save. (The IPersistFile interface is a standard COM interface supported by the ITask interface.)
  4. Call ITask::Release to release all resources. (Note that Release is an IUnknown method inherited by ITask.)
For a code example using | See
C++ | C/C++ Code Example: Creating a Task Using NewWorkItem


C/C++ Code Example: Creating a Task Using NewWorkItem

This example creates a single task.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <objidl.h>
#include <wchar.h>
#include <stdio.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;
  ITaskScheduler *pITS;

  /////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  /////////////////////////////////////////////////////////////////
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
     hr = CoCreateInstance(CLSID_CTaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskScheduler,
                           (void **) &pITS);
     if (FAILED(hr))
     {
        CoUninitialize();
        return 1;
     }
  }
  else
  {
     return 1;
  }

  /////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::NewWorkItem to create new task.
  /////////////////////////////////////////////////////////////////
  LPCWSTR pwszTaskName;
  ITask *pITask;
  IPersistFile *pIPersistFile;
  pwszTaskName = L"Test Task";

  hr = pITS->NewWorkItem(pwszTaskName,           // Name of task
                         CLSID_CTask,            // Class identifier
                         IID_ITask,              // Interface identifier
                         (IUnknown**)&pITask); // Address of task interface

  pITS->Release();                               // Release object
  if (FAILED(hr))
  {
     CoUninitialize();
     fprintf(stderr, "Failed calling NewWorkItem, error = 0x%x\n",hr);
     return 1;
  }

  /////////////////////////////////////////////////////////////////
  // Call IUnknown::QueryInterface to get a pointer to
  // IPersistFile and IPersistFile::Save to save
  // the new task to disk.
  /////////////////////////////////////////////////////////////////

  hr = pITask->QueryInterface(IID_IPersistFile,
                              (void **)&pIPersistFile);

  pITask->Release();
  if (FAILED(hr))
  {
     CoUninitialize();
     fprintf(stderr, "Failed calling QueryInterface, error = 0x%x\n",hr);
     return 1;
  }

  hr = pIPersistFile->Save(NULL,
                           TRUE);
  pIPersistFile->Release();
  if (FAILED(hr))
  {
     CoUninitialize();
     fprintf(stderr, "Failed calling Save, error = 0x%x\n",hr);
     return 1;
  }

  printf("Created task.\n");
  return 0;
}


Enumerating Tasks Example

To enumerate tasks, you must call ITaskScheduler::Enum to create an enumeration object. Then, use the enumeration object's IEnumWorkItems interface to enumerate the tasks in the Scheduled Tasks folder.

To enumerate the tasks in the Scheduled Tasks folder

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (This example assumes that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Enum to get an enumeration object.
  3. Call IEnumWorkItems::Next to retrieve the tasks. (This example tries to retrieve five tasks with each call.)
  4. Process the tasks returned. (This example simply prints the name of each task to the screen.
  5. Release resources. Call CoTaskMemFree to free memory used for names.
For a code example using | See
C++ | C/C++ Code Example: Enumerating Tasks


C/C++ Code Example: Enumerating Tasks

This example enumerates all the tasks in the Scheduled Tasks folder of the local computer, printing the name of each task on the screen.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

#define TASKS_TO_RETRIEVE          5

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;
  ITaskScheduler *pITS;

  /////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and
  // then CoCreateInstance to get the Task Scheduler object.
  /////////////////////////////////////////////////////////////////
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return hr;
    }
  }
  else
  {
    return hr;
  }

  /////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Enum to get an enumeration object.
  /////////////////////////////////////////////////////////////////
  IEnumWorkItems *pIEnum;
  hr = pITS->Enum(&pIEnum);
  pITS->Release();
  if (FAILED(hr))
  {
    CoUninitialize();
    return hr;
  }

  /////////////////////////////////////////////////////////////////
  // Call IEnumWorkItems::Next to retrieve tasks. Note that
  // this example tries to retrieve five tasks for each call.
  /////////////////////////////////////////////////////////////////
  LPWSTR *lpwszNames;
  DWORD dwFetchedTasks = 0;
  while (SUCCEEDED(pIEnum->Next(TASKS_TO_RETRIEVE,
                                &lpwszNames,
                                &dwFetchedTasks))
                  && (dwFetchedTasks != 0))
  {
    ///////////////////////////////////////////////////////////////
    // Process each task. Note that this example prints the
    // name of each task to the screen.
    //////////////////////////////////////////////////////////////
    while (dwFetchedTasks)
    {
       wprintf(L"%s\n", lpwszNames[--dwFetchedTasks]);
       CoTaskMemFree(lpwszNames[dwFetchedTasks]);
    }
    CoTaskMemFree(lpwszNames);
  }

  pIEnum->Release();
  CoUninitialize();
  return ERROR_SUCCESS;
}


Starting a Task Example

To start a task, call the Run method of the ITask interface. Run is an asynchronous method that attempts to execute the task and returns as soon as the task has started. The Task Scheduler service must be running for this method to succeed.

To start a task

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (This example assumes that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. Note that this example gets the "Test Task" task.
  3. Call Run to start the task. Note that this method is inherited by the ITask interface.
  4. Continue processing as needed.
  5. Call ITask::Release to free resources and CoUninitialize to uninitialize COM. This example calls Release to free the pointer to the ITask interface. (Note that Release is an IUnknown method inherited by ITask.)
For a code example of | See
Starting an existing task | C/C++ Code Example: Starting a Task


C/C++ Code Example: Starting a Task

This example attempts to run an existing task. It assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>
#include<stdio.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;
  ITaskScheduler *pITS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
     hr = CoCreateInstance(CLSID_CTaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskScheduler,
                           (void **) &pITS);
     if (FAILED(hr))
     {
        CoUninitialize();
        return 1;
     }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  pITS->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITaskScheduler::Activate; error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::Run to start execution of "Test Task".
  ///////////////////////////////////////////////////////////////////

  hr = pITask->Run();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITask::Run, error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  pITask->Release();
  CoUninitialize();
  return 0;
}


Editing a Work Item using Property Pages

You can edit the properties of a work item by using the graphic user interface provided by the Task Scheduler Service. (Currently the only valid work items are tasks.)

To edit a task using its property pages

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (These examples assume that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. (Note that tasks are currently the only valid type of work item.)
  3. Call IScheduledWorkItem::EditWorkItem to display the property pages for the task.
  4. Edit the properties of the task as needed, then click OK to accept the new values and remove the displayed property pages.
For a code example of | See
Editing a know task | C/C++ Code Example: Editing a Work Item


C/C++ Code Example: Editing a Work Item

This example displays the property pages for a known task, allowing a user edit the properties of the work item. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library then          //
  // CoCreateInstance to get the Task Scheduler object.            //
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  //Release ITaskScheduler interface
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate, ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::EditWorkItem. Note that this method is
  // inherited from IScheduledWorkItem.
  ///////////////////////////////////////////////////////////////////
  HWND hParent = NULL;
  DWORD dwReserved = 0;

  hr = pITask->EditWorkItem(hParent,
                            dwReserved);
  // Release ITask interface
  pITask->Release();
  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::EditWorkItem, ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  CoUninitialize();
  return 0;
}


Retrieving Work Item Property Examples

To retrieve the properties of a work item, call ITaskScheduler::Activate to retrieve the interface of the work item object, then call the appropriate method to retrieve the task property you are interested in. Currently the only valid work items are tasks.

The code examples listed at the bottom of this page show how to retrieve properties that apply to all work items. For other properties that are unique to tasks, see Setting Task Property Examples.

Note In the following code example, all interfaces are released after they are no longer needed.

Note that if you are retrieving a string property (such as comment for a work item), you must call CoTaskMemFree to free the memory allocated for the returned string.

To retrieve a task property

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (These examples assume that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. (Note that tasks are currently the only valid type of work item.)
  3. Call the appropriate method to retrieve the property you are interested in.
  4. Process the property as needed. (These examples simply print the property to the screen.)
  5. If the returned property is a string, call CoTaskMemFree to free the memory allocated for the returned string.
For a code example of | See
Retrieving the account information of a task | C/C++ Code Example: Retrieving Task Account Information
Retrieving the comment string of a task | C/C++ Code Example: Retrieving a Task Comment
Retrieving the creator of a task | C/C++ Code Example: Retrieving the Task Creator
Retrieving the last exit code returned when running a task | C/C++ Code Example: Retrieving Task Exit Code
Retrieving the idle wait time of a task | C/C++ Code Example: Retrieving Task Idle-wait Time
Retrieving the last time a task ran | C/C++ Code Example: Retrieving the Task MostRecentRun Time
Retrieving the next time a task is scheduled to run | C/C++ Code Example: Retrieving the Task NextRun Time
Retrieving the run times of a task | C/C++ Code Example: Retrieving Task Run Times
Retrieving the status of a task | C/C++ Code Example: Retrieving Task Status


C/C++ Code Example: Retrieving Task Account Information

This example retrieves the account information of a known task, then displays the account name on the screen. The example assumes that the task, Test Task, already exists on the local computer and that the Task Scheduler is running.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  //Release ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetAccountInformation. Note that this method is
  // inherited from IScheduledWorkItem.
  ///////////////////////////////////////////////////////////////////
  LPWSTR ppwszAccountName;

  hr = pITask->GetAccountInformation(&ppwszAccountName);

  // Release the ITask interface.
  pITask->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::GetAccountInformation: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  wprintf(L"The account name for Test Task is: ");
  wprintf(L"  %s\n",ppwszAccountName);

  CoTaskMemFree(ppwszAccountName);
  CoUninitialize();
  return 0;
}


C/C++ Code Example: Retrieving a Task Comment

This example retrieves the comment string of a known task, and then displays the comment string on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  //Release ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetComment. Note that this method is
  // inherited from IScheduledWorkItem.
  ///////////////////////////////////////////////////////////////////
  LPWSTR ppwszComment;

  hr = pITask->GetComment(&ppwszComment);

  // Release the ITask interface.
  pITask->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::GetComment: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  wprintf(L"The comment for Test Task is: ");
  wprintf(L"  %s\n",ppwszComment);

  ///////////////////////////////////////////////////////////////////
  // Call CoTaskMemFree to free the string.
  ///////////////////////////////////////////////////////////////////
  CoTaskMemFree(ppwszComment);

  CoUninitialize();
  return 0;
}


C/C++ Code Example: Retrieving the Task Creator

This example retrieves the name of the creator of the task and displays it on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  //Release ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetCreator. Note that this method is
  // inherited from IScheduledWorkItem.
  ///////////////////////////////////////////////////////////////////
  LPWSTR ppwszCreator;

  hr = pITask->GetCreator(&ppwszCreator);

  // Release the ITask interface.
  pITask->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::GetCreator: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  wprintf(L"The creator of Test Task is: ");
  wprintf(L"  %s\n",ppwszCreator);

  ///////////////////////////////////////////////////////////////////
  // Call CoTaskMemFree to free the string.
  ///////////////////////////////////////////////////////////////////
  CoTaskMemFree(ppwszCreator);

  CoUninitialize();
  return 0;
}


C/C++ Code Example: Retrieving Task Exit Code

This example retrieves the last exit code returned by a known task. (A returned value of "0" indicates the task was never run.) The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"TestTask";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetExitCode. Note that this method is
  // inherited from IScheduledWorkItem.
  ///////////////////////////////////////////////////////////////////
  DWORD pdwExitCode;

  hr = pITask->GetExitCode(&pdwExitCode);

  // Release ITask interface.
  pITask->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::GetExitCode: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  wprintf(L"The last exit code of Test Task is: %d\n", pdwExitCode);

  CoUninitialize();
  return 0;
}


C/C++ Code Example: Retrieving Task Idle-wait Time

This example retrieves the idle-wait time of the task and displays it on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetIdleWait. Note that this method is
  // inherited from IScheduledWorkItem.
  ///////////////////////////////////////////////////////////////////
  WORD pwIdleMinutes;
  WORD pwDeadlineMinutes;

  hr = pITask->GetIdleWait(&pwIdleMinutes,
                           &pwDeadlineMinutes);

  // Release the ITask interface.
  pITask->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::GetIdleWait: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  wprintf(L"The idle wait of Test Task is: \n");
  wprintf(L" %d minutes\n", pwIdleMinutes);
  wprintf(L" %d minutes\n", pwDeadlineMinutes);

  CoUninitialize();
  return 0;
}


C/C++ Code Example: Retrieving the Task MostRecentRun Time

This example retrieves the time the task was last run and displays it on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <wchar.h>
#include <stdio.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetMostRecentRunTime and display the most recent
  // run time of this task.
  ///////////////////////////////////////////////////////////////////

  SYSTEMTIME pstLastRun;

  hr = pITask->GetMostRecentRunTime(&pstLastRun);

  // Release the ITask interface.
  pITask->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling GetMostRecentRunTime: ");
    wprintf(L"error = 0x%x\n", hr);
    CoUninitialize();
    return 1;
  }

  wprintf(L"The most recent run time for this task was: \n");
  wprintf(L"  %u/%u/%u \t %u:%02u\n", pstLastRun.wMonth,
                                      pstLastRun.wDay,
                                      pstLastRun.wYear,
                                      pstLastRun.wHour,
                                      pstLastRun.wMinute);

  CoUninitialize();

  return 0;
}


C/C++ Code Example: Retrieving the Task NextRun Time

This example retrieves the next time the task is scheduled to run and displays that time on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <wchar.h>
#include <stdio.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetNextRunTime and display next run time of
  // this task.
  ///////////////////////////////////////////////////////////////////

  SYSTEMTIME pstNextRun;

  hr = pITask->GetNextRunTime(&pstNextRun);

  // Release the ITask interface.
  pITask->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling GetNextRunTime: ");
    wprintf(L"error = 0x%x\n", hr);
    CoUninitialize();
    return 1;
  }

  wprintf(L"The next runtime for this task is: \n");
  wprintf(L"  %u/%u/%u \t %u:%02u\n", pstNextRun.wMonth,
                                      pstNextRun.wDay,
                                      pstNextRun.wYear,
                                      pstNextRun.wHour,
                                      pstNextRun.wMinute);

  CoUninitialize();

  return 0;
}


C/C++ Code Example: Retrieving Task Run Times

This example retrieves the run times of the task and displays them on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <wchar.h>
#include <stdio.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release the ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetRunTimes and display the next five run times for
  // this task.
  ///////////////////////////////////////////////////////////////////

  SYSTEMTIME stNow;
  LPSYSTEMTIME pstListOfTimes;
  LPSYSTEMTIME pstListBegin;
  WORD wCountOfRuns = 5;

  GetSystemTime(&stNow);
  hr = pITask->GetRunTimes(&stNow,
                           NULL,
                           &wCountOfRuns,
                           &pstListBegin);
  pstListOfTimes = pstListBegin;

  // Release the ITask interface.
  pITask->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling GetRunTimes: ");
    wprintf(L"error = 0x%x\n", hr);
    CoUninitialize();
    return 1;
  }

  wprintf(L"The next %u runtimes for this task are: \n",wCountOfRuns);

  for (WORD i = 0; i < wCountOfRuns; i++)
  {
    wprintf(L"\t%u - %u/%u/%u \t %u:%u\n", i+1, pstListOfTimes->wMonth,
                                                pstListOfTimes->wDay,
                                                pstListOfTimes->wYear,
                                                pstListOfTimes->wHour,
                                                pstListOfTimes->wMinute);
    pstListOfTimes++;
  }

  CoTaskMemFree(pstListBegin);
  CoUninitialize();

  return 0;
}


C/C++ Code Example: Retrieving Task Status

This example retrieves the current status of the task and displays it on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetStatus. Note that this method is
  // inherited from IScheduledWorkItem.
  ///////////////////////////////////////////////////////////////////
  HRESULT phrStatus;

  hr = pITask->GetStatus(&phrStatus);

  // Release the ITask interface.
  pITask->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::GetStatus: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  wprintf(L"The status of Test Task is: ");

  switch(phrStatus)
  {
  case SCHED_S_TASK_READY:
       wprintf(L"  SCHED_S_TASK_READY\n");
       break;
  case SCHED_S_TASK_RUNNING:
       wprintf(L"  SCHED_S_TASK_RUNNING\n");
       break;
  case SCHED_S_TASK_NOT_SCHEDULED:
       wprintf(L"  SCHED_S_TASK_NOT_SCHEDULED\n");
       break;
  default:
       wprintf(L"  unknown status flag!\n");
  }

  CoUninitialize();
  return 0;
}


Setting Work Item Property Examples

To set the properties of a work item, call ITaskScheduler::Activate to retrieve the interface of the work item object, then call the appropriate method to set the task property you are interested in. Currently the only valid work items are tasks.

The code examples listed at the bottom of the page show how to set properties that apply to all work items. For other properties that are unique to tasks, see Setting Task Property Examples.

Note In the following code example, all interfaces are released after they are no longer needed.

In the following examples, the modified object is always saved to disk by a call to IPersistFile::Save. (The IPersistFile interface is a standard COM interface inherited by the task object.)

To set a task property

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (These examples assume that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. Note that task are the only valid work item.
  3. Call the appropriate IScheduledWorkItem method to set the property you are interested in. Note that IScheduledWorkItem methods are inherited by the ITask interface.
  4. Call IPersistFile::Save to store the modified task object to disk.
For a code example of | See
Setting the account information of a task | C/C++ Code Example: Setting Task Account Information
Setting the comment of a task | C/C++ Code Example: Setting Task Comment


C/C++ Code Example: Setting Task Account Information

This example sets the account information for a known task. The example assumes that the task, Test Task, already exists on the local computer and that the Task Scheduler service is running.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;

  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release the ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::SetAccountInformation to specify the account name
  // and the account password for Test Task.
  ///////////////////////////////////////////////////////////////////
  LPCWSTR pwszAccountName = L"myAccount";
  LPCWSTR pwszPassword = L"myPassword";
  hr = pITask->SetAccountInformation(pwszAccountName,
                                     pwszPassword);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::SetAccountInformation: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call IPersistFile::Save to save the modified task to disk.
  ///////////////////////////////////////////////////////////////////
  IPersistFile *pIPersistFile;

  hr = pITask->QueryInterface(IID_IPersistFile,
                              (void **)&pIPersistFile);

  // Release the ITask interface.
  pITask->Release();

  hr = pIPersistFile->Save(NULL,
                           TRUE);

  // Release the IPersistFile interface.
  pIPersistFile->Release();

  wprintf(L"Set the account name to %s and ", pwszAccountName);
  wprintf(L"and the account password to %s.\n", pwszPassword);
  CoUninitialize();
  return 0;
}


C/C++ Code Example: Setting Task Comment

This example sets the comment for a known task. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;

  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release the ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::SetComment to specify the account name
  // and the account password for Test Task.
  ///////////////////////////////////////////////////////////////////
  LPCWSTR pwszComment = L"This task is used to test the Task Scheduler APIs.";

  hr = pITask->SetComment(pwszComment);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::SetComment: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call IPersistFile::Save to save the modified task to disk.
  ///////////////////////////////////////////////////////////////////
  IPersistFile *pIPersistFile;

  hr = pITask->QueryInterface(IID_IPersistFile,
                              (void **)&pIPersistFile);

  // Release the ITask interface.
  pITask->Release();

  hr = pIPersistFile->Save(NULL,
                           TRUE);

  // Release the IPersistFile interface.
  pIPersistFile->Release();

  wprintf(L"Set the comment for Test Task.\n");
  CoUninitialize();
  return 0;
}


Retrieving Task Property Examples

To retrieve the properties of a task, call ITaskScheduler::Activate to get retrieve the interface of the task object, then call the appropriate ITask method to retrieve the task property you are interested in. The code examples listed at the bottom of the page show how to retrieve the different task properties.

The code examples listed at the bottom of the page show how to get properties that are unique to task objects. For other work item properties that also apply to tasks, see Retrieving Work Item Examples.

Note In the following code example, all interfaces are released after they are no longer needed.

Note that if you are retrieving a string property (such as the application name, parameters, or working directory), you must call CoTaskMemFree to free the memory allocated for the returned string.

To retrieve a task property

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (These examples assume that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. Note these examples get the "Test Task" task.
  3. Call the appropriate ITask method to retrieve the property you are interested in.
  4. Process the property as needed. (These examples print the property to the screen.)
  5. If the returned property is a string, call CoTaskMemFree to free the memory allocated for the returned string.
For a code example of | See
Retrieving the application associated with the task | C/C++ Code Example: Retrieving the Task Application Name
Retrieving the maximum run time of the task | C/C++ Code Example: Retrieving the Task MaxRunTime
Retrieving the command line parameters run by the task | C/C++ Code Example: Retrieving Task Parameters
Retrieving the priority level of the task | C/C++ Code Example: Retrieving Task Priority
Retrieving the working directory associated with the task | C/C++ Code Example: Retrieving the Task Working Directory


C/C++ Code Example: Retrieving the Task Application Name

This example retrieves the name of the application associated with a given task, then displays that name on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////

  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
     hr = CoCreateInstance(CLSID_CTaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskScheduler,
                           (void **) &pITS);
     if (FAILED(hr))
     {
        CoUninitialize();
        return 1;
     }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  pITS->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITaskScheduler::Activate; error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetApplicationName to display the name of the
  // application associated with "Test Task".
  ///////////////////////////////////////////////////////////////////

  LPWSTR lpwszApplicationName;
  hr = pITask->GetApplicationName(&lpwszApplicationName);
  pITask->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITask::GetApplicationName\n");
     wprintf(L" error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Process the returned string.
  ///////////////////////////////////////////////////////////////////

  wprintf(L"Test Task is associated with: %s\n", lpwszApplicationName);

  ///////////////////////////////////////////////////////////////////
  // Call CoTaskMemFree to free resources.
  ///////////////////////////////////////////////////////////////////

  CoTaskMemFree(lpwszApplicationName);
  CoUninitialize();
  return 0;
}


C/C++ Code Example: Retrieving the Task MaxRunTime

This example retrieves the maximum amount of time the task can run (in milliseconds), and displays that number on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
..
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
     hr = CoCreateInstance(CLSID_CTaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskScheduler,
                           (void **) &pITS);
     if (FAILED(hr))
     {
        CoUninitialize();
        return 1;
     }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  pITS->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITaskScheduler::Activate;\n");
     wprintf(L"error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetMaxRunTime to display the maximum time Test Task
  // is allowed to run.
  ///////////////////////////////////////////////////////////////////

  DWORD pdwRunTime;
  hr = pITask->GetMaxRunTime(&pdwRunTime);
  pITask->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITask::GetMaxRunTime: \n");
     wprintf(L"error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  wprintf(L"Test Task can run for %d milliseconds\n", pdwRunTime);
  CoUninitialize();
  return 0;
}


C/C++ Code Example: Retrieving Task Parameters

This example retrieves the parameter string that is executed when the task is run, then displays string on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////

  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
     hr = CoCreateInstance(CLSID_CTaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskScheduler,
                           (void **) &pITS);
     if (FAILED(hr))
     {
        CoUninitialize();
        return 1;
     }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  pITS->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITaskScheduler::Activate; error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetParameters to display the parameters string
  // associated with "Test Task".
  ///////////////////////////////////////////////////////////////////

  LPWSTR lpwszParameters;
  hr = pITask->GetParameters(&lpwszParameters);
  pITask->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITask::GetApplicationName\n");
     wprintf(L" error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Process returned parameter string.
  ///////////////////////////////////////////////////////////////////

  wprintf(L"Test Task is associated with the following parameters:\n");
  wprintf(L"  %s\n", lpwszParameters);

  ///////////////////////////////////////////////////////////////////
  // Call CoTaskMemFree to free resources.
  ///////////////////////////////////////////////////////////////////

  CoTaskMemFree(lpwszParameters);
  CoUninitialize();
  return 0;
}


C/C++ Code Example: Retrieving the Task Priority

Platform SDK: Task Scheduler

C/C++ Code Example: Retrieving Task Priority

This example retrieves the priority level of a task, then displays the path to the working directory on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
     hr = CoCreateInstance(CLSID_CTaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskScheduler,
                           (void **) &pITS);
     if (FAILED(hr))
     {
        CoUninitialize();
        return 1;
     }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  pITS->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITaskScheduler::Activate: error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetPriority to retrieve the priority level
  // of Test Task.
  ///////////////////////////////////////////////////////////////////

  DWORD pdwPriority;
  hr = pITask->GetPriority(&pdwPriority);
  pITask->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITask::GetPriority: error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }
  if(pdwPriority == HIGH_PRIORITY_CLASS)
  {
     wprintf(L"Test Task is a high priority task.\n");
  }
  else
  {
     wprintf(L"Test Task is not a high priority task.\n");
  }

  CoUninitialize();
  return 0;

}


C/C++ Code Example: Retrieving the Task Working Directory

This example retrieves the working directory associated with a task, then displays the path to the working directory on the screen. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////

  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
     hr = CoCreateInstance(CLSID_CTaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskScheduler,
                           (void **) &pITS);
     if (FAILED(hr))
     {
        CoUninitialize();
        return 1;
     }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  pITS->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITaskScheduler::Activate: error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetWorkingDirectory to display the working
  // directory associated with "Test Task".
  ///////////////////////////////////////////////////////////////////

  LPWSTR lpwszWorkDir;
  hr = pITask->GetWorkingDirectory(&lpwszWorkDir);
  pITask->Release();
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITask::GetWorkingDirectory: \n");
     wprintf(L" error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Process returned string.
  ///////////////////////////////////////////////////////////////////

  wprintf(L"Test Task is associated with : %s\n", lpwszWorkDir);

  ///////////////////////////////////////////////////////////////////
  // Call CoTaskMemFree to free resources.
  ///////////////////////////////////////////////////////////////////

  CoTaskMemFree(lpwszApplicationName);
  CoUninitialize();
  return 0;
}


Setting Task Property Examples

To set the properties of a task, call ITaskScheduler::Activate to retrieve the interface of the task object, then call the appropriate ITask method to set the task property you are interested in.

The code examples listed at the bottom of the page show how to set properties that are unique to task objects. For other work item properties that also apply to tasks, see Setting Work Item Property Examples.

Note In the following code example, all interfaces are released after they are no longer needed.

In the following examples, the modified task object is always saved to disk by a call to IPersistFile::Save. (The IPersistFile interface is a standard COM interface inherited by the task object.)

To set a task property

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (These examples assume that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. Note these examples get the "Test Task" task.
  3. Call the appropriate ITask method to set the property you are interested in.
  4. Call IPersistFile::Save to store the modified task object to disk.
For a code example of | See
Setting the application associated with the task | C/C++ Code Example: Setting Application Name
Setting the maximum run time of the task | C/C++ Code Example: Setting MaxRunTime
Setting the command line parameters run by the task | C/C++ Code Example: Setting Task Parameters
Setting the priority level of the task | C/C++ Code Example: Setting Task Priority
Setting the working directory associated with the task | C/C++ Code Example: Setting Working Directory


C/C++ Code Example: Setting Application Name

This example sets the name of the application associated with a known task. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;

  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release the ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::SetComment to specify the account name
  // and the account password for Test Task.
  ///////////////////////////////////////////////////////////////////
  LPCWSTR pwszApplicationName = L"C:\\WINNT40\\notepad.exe";

  hr = pITask->SetApplicationName(pwszApplicationName);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::SetApplicationName: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call IPersistFile::Save to save the modified task to disk.
  ///////////////////////////////////////////////////////////////////
  IPersistFile *pIPersistFile;

  hr = pITask->QueryInterface(IID_IPersistFile,
                              (void **)&pIPersistFile);

  // Release the ITask interface.
  pITask->Release();

  hr = pIPersistFile->Save(NULL,
                           TRUE);

  // Release the IPersistFile interface.
  pIPersistFile->Release();

  wprintf(L"Set the application name for Test Task.\n");
  CoUninitialize();
  return 0;
}


C/C++ Code Example: Setting MaxRunTime

This example sets the maximum run time (set in milliseconds) of a known task. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;

  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release the ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::SetMaxRunTime to specify the maximum amount
  // of time the task will run.
  ///////////////////////////////////////////////////////////////////
  DWORD dwMaxRunTime = (1000*60*5);

  hr = pITask->SetMaxRunTime(dwMaxRunTime);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::SetMaxRunTime: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call IPersistFile::Save to save the modified task to disk.
  ///////////////////////////////////////////////////////////////////
  IPersistFile *pIPersistFile;

  hr = pITask->QueryInterface(IID_IPersistFile,
                              (void **)&pIPersistFile);

  // Release the ITask interface.
  pITask->Release();

  hr = pIPersistFile->Save(NULL,
                           TRUE);

  // Release the IPersistFile interface.
  pIPersistFile->Release();

  wprintf(L"The maximum run time is set to 5 minutes.\n");

  CoUninitialize();
  return 0;
}


C/C++ Code Example: Setting Task Parameters

This example clears all command line parameters associated with a known task. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;

  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                     (IUnknown**) &pITask);

  // Release the ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::SetParameters to L"" to clear the parameters for
  // Test Task.
  ///////////////////////////////////////////////////////////////////
  LPCWSTR pwszParameters = L"";

  hr = pITask->SetParameters(pwszParameters);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::SetParameters: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call IPersistFile::Save to save the modified task to disk.
  ///////////////////////////////////////////////////////////////////
  IPersistFile *pIPersistFile;

  hr = pITask->QueryInterface(IID_IPersistFile,
                              (void **)&pIPersistFile);

  // Release the ITask interface.
  pITask->Release();

  hr = pIPersistFile->Save(NULL,
                           TRUE);

  // Release the IPersistFile interface.
  pIPersistFile->Release();

  wprintf(L"Cleared the parameters of TestTask.\n");

  CoUninitialize();
  return 0;
}


C/C++ Code Example: Setting Task Priority

This example clears all command line parameters associated with a known task. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;

  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                     (IUnknown**) &pITask);

  // Release the ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::SetPriority to specify the priority level of
  // Test Task.
  ///////////////////////////////////////////////////////////////////
  DWORD dwPriority = HIGH_PRIORITY_CLASS;

  hr = pITask->SetPriority(dwPriority);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::SetPriority: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call IPersistFile::Save to save the modified task to disk.
  ///////////////////////////////////////////////////////////////////
  IPersistFile *pIPersistFile;

  hr = pITask->QueryInterface(IID_IPersistFile,
                              (void **)&pIPersistFile);

  // Release the ITask interface.
  pITask->Release();

  hr = pIPersistFile->Save(NULL,
                           TRUE);

  // Release the IPersistFile interface.
  pIPersistFile->Release();

  wprintf(L"Set the priority of TestTask to HIGH_PRIORITY_CLASS.\n");

  CoUninitialize();
  return 0;
}


C/C++ Code Example: Setting Working Directory

This example sets the working directory of a know task. The example assumes that the task, Test Task, already exists on the local computer.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;

  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                     (IUnknown**) &pITask);

  // Release the ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::SetWorkingDirectory to specify the current
  // working directory for Test Task.
  ///////////////////////////////////////////////////////////////////
  LPCWSTR pwszWorkingDirectory = L"C://Temp";

  hr = pITask->SetWorkingDirectory(pwszWorkingDirectory);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::SetWorkingDirectory: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call IPersistFile::Save to save the modified task to disk.
  ///////////////////////////////////////////////////////////////////
  IPersistFile *pIPersistFile;

  hr = pITask->QueryInterface(IID_IPersistFile,
                              (void **)&pIPersistFile);

  // Release the ITask interface.
  pITask->Release();

  hr = pIPersistFile->Save(NULL,
                          TRUE);

  // Release the IPersistFile interface.
  pIPersistFile->Release();

  wprintf(L"Set the working directory to C:/Temp.\n");

  CoUninitialize();
  return 0;
}


Retrieving a Task Page Example

To retrieve a task page you must call ITask::QueryInterface to retrieve the IProvideTaskPage interface, then call IProvideTaskPage::GetPage. The GetPage method returns a handle to the page, which can then be used to display the page you requested.

Note In the following code example, all interfaces are released after they are no longer needed.

To Create a new trigger

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (This example assumes that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. (Note these examples get the "Test Task" task.)
  3. Call ITask::QueryInterface to retrieve the IProvideTaskPage interface and IProvideTaskPage::GetPage to retrieve the page.
  4. Using the returned page handle, display the page.
For a code example using | See
C++ | Retrieving a Task Page


C/C++ Code Example: Retrieving a Task Page

This example retrieves and displays the Task page of a known task. Note that in this example, all interfaces are released when they are no longer needed.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
       CoUninitialize();
       return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  // Release the ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::QueryInterface to retrieve the IProvideTaskPage
  // interface, and call IProvideTaskPage::GetPage to retrieve the
  // task page.
  ///////////////////////////////////////////////////////////////////
  TASKPAGE tpType = TASKPAGE_TASK;
  BOOL fPersistChanges = TRUE;
  HPROPSHEETPAGE phPage;

  IProvideTaskPage *pIProvTaskPage;
  hr = pITask->QueryInterface(IID_IProvideTaskPage,
                              (void **)&pIProvTaskPage);
  // Release the ITask interface.
  pITask->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::QueryInterface: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  hr = pIProvTaskPage->GetPage(tpType,
                               fPersistChanges,
                               &phPage);

  // Release the IProvideTaskPage interface.
  pIProvTaskPage->Release();

  if (FAILED(hr))
  {
     wprintf(L"Failed calling IProvideTaskPage::GetPage: ");
     wprintf(L"error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  //////////////////////////////////////////////////////////////////
  // Display the page using additional code
  //////////////////////////////////////////////////////////////////

  PROPSHEETHEADER psh;
  ZeroMemory(&psh, sizeof(PROPSHEETHEADER));
  psh.dwSize = sizeof(PROPSHEETHEADER);
  psh.dwFlags = PSH_DEFAULT | PSH_NOAPPLYNOW;
  psh.phpage = &phPage;
  psh.nPages = 1;

  int psResult = PropertySheet(&psh);
  if (psResult <= 0)
  {
    wprintf(L"Failed to create the property page: ");
    wprintf(L"0x%x\n", GetLastError());
  }

  CoUninitialize();
  return 0;
}


Creating a New Trigger

To create a trigger you must use three interfaces. IScheduledWorkItem provides the IScheduledWorkItem::CreateTrigger method for creating the trigger object, ITaskTrigger provides the ITaskTrigger::SetTrigger method for setting the criteria for the trigger, and the COM interface IPersistFile provides a Save method for saving the new trigger to disk.

To Create a new trigger

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (This example assumes that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. (Note these examples get the "Test Task" task.)
  3. Call CreateTrigger to create a trigger object. (Note that CreateTrigger is inherited from IScheduledWorkItem.)
  4. Define a TASK_TRIGGER structure. Note that wBeginDay, wBeginMonth, and wBeginYear members of TASK_TRIGGER must be set to a valid day, month, and year respectively.
  5. Call ITaskTrigger::SetTrigger to set the trigger criteria.
  6. Save the task with the new trigger to disk using IPersistFile::Save. (The IPersistFile interface is a standard COM interface supported by the ITask interface.)
  7. Call Release to release all resources. (Note that Release is an IUnknown method inherited by ITask.)
For a code example using | See
C++ | C/C++ Code Example: Creating a Task Trigger


C/C++ Code Example: Creating a Task Trigger

This example creates a new trigger for an existing task.

#include <windows.h>
#include <winbase.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;
  ITaskScheduler *pITS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);
  if (FAILED(hr))
  {
     wprintf(L"Failed calling ITaskScheduler::Activate: ");
     wprintf(L"error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }
    pITS->Release();

  ///////////////////////////////////////////////////////////////////
  // Call ITask::CreateTrigger to create new trigger.
  ///////////////////////////////////////////////////////////////////

  ITaskTrigger *pITaskTrigger;
  WORD piNewTrigger;
  hr = pITask->CreateTrigger(&piNewTrigger,
                             &pITaskTrigger);
  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::CreatTrigger: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  //////////////////////////////////////////////////////
  // Define TASK_TRIGGER structure. Note that wBeginDay,
  // wBeginMonth, and wBeginYear must be set to a valid
  // day, month, and year respectively.
  //////////////////////////////////////////////////////

  TASK_TRIGGER pTrigger;
  ZeroMemory(&pTrigger, sizeof (TASK_TRIGGER));

  // Add code to set trigger structure?
  pTrigger.wBeginDay =1;                  // Required
  pTrigger.wBeginMonth =1;                // Required
  pTrigger.wBeginYear =1999;              // Required
  pTrigger.cbTriggerSize = sizeof (TASK_TRIGGER);
  pTrigger.wStartHour = 13;
  pTrigger.TriggerType = TASK_TIME_TRIGGER_DAILY;
  pTrigger.Type.Daily.DaysInterval = 1;

  ///////////////////////////////////////////////////////////////////
  // Call ITaskTrigger::SetTrigger to set trigger criteria.
  ///////////////////////////////////////////////////////////////////

  hr = pITaskTrigger->SetTrigger (&pTrigger);
  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskTrigger::SetTrigger: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call IPersistFile::Save to save trigger to disk.
  ///////////////////////////////////////////////////////////////////

  IPersistFile *pIPersistFile;
  hr = pITask->QueryInterface(IID_IPersistFile,
                              (void **)&pIPersistFile);
  hr = pIPersistFile->Save(NULL,
                           TRUE);

  wprintf(L"The trigger was created and IPersistFile::Save was \n");
  wprintf(L"called to save the new trigger to disk.\n");

  ///////////////////////////////////////////////////////////////////
  // Release resources.
  ///////////////////////////////////////////////////////////////////

  pITask->Release();
  pITaskTrigger->Release();
  pIPersistFile->Release();
  CoUninitialize();
  return 0;
}


Creating an Idle Trigger Example

To create an idle trigger, you must specify an idle trigger when you create the trigger, and you must set the idle time for the task.

After creating the idle trigger, call IPersistFile::Save to save the new trigger to disk.

To create an idle trigger for a known task

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (This example assumes that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. (Note these examples get the "Test Task" task.)
  3. Call SetIdleWait to set how long the system must remain idle before the trigger will fire. (Note that SetIdleWait is inherited from IScheduledWorkItem.)
  4. Define the TASK_TRIGGER structure and call CreateTrigger to create the idle trigger. (Note that CreateTrigger is inherited from IScheduledWorkItem.)
  5. Save the task with the new idle trigger to disk using IPersistFile::Save. (The IPersistFile interface is a standard COM interface supported by the ITask interface.)
  6. Call ITask::Release to release all resources. (Note that Release is an IUnknown method inherited by ITask.)
For a code example using | See
C++ | C/C++ Code Example: Creating an Idle Trigger


C/C++ Code Example: Creating an Idle Trigger

This example creates an idle trigger for an existing task.

#include <windows.h>
#include <winbase.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;
  ITaskScheduler *pITS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::SetIdleWait to specify idle time.
  ///////////////////////////////////////////////////////////////////

  WORD wIdleMinutes = 3;
  WORD wDeadlineMinutes = 5;

  hr = pITask->SetIdleWait(wIdleMinutes,
                           wDeadlineMinutes);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::SetIdleWait: ");
    wprintf(L"error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

 ///////////////////////////////////////////////////////////////////
  // Call ITask::CreateTrigger to create new trigger.
  ///////////////////////////////////////////////////////////////////

  ITaskTrigger *pITaskTrigger;
  WORD piNewTrigger;

  hr = pITask->CreateTrigger(&piNewTrigger,
                             &pITaskTrigger);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::CreatTrigger: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Define TASK_TRIGGER structure and call ITask::CreateTrigger
  // to create the idle trigger.
  ///////////////////////////////////////////////////////////////////
  TASK_TRIGGER pTrigger;
  ZeroMemory(&pTrigger, sizeof (TASK_TRIGGER));

  // Add code to set trigger structure.
  pTrigger.wBeginDay = 1;
  pTrigger.wBeginMonth = 1;
  pTrigger.wBeginYear =1999;
  pTrigger.cbTriggerSize = sizeof (TASK_TRIGGER);
  pTrigger.TriggerType = TASK_EVENT_TRIGGER_ON_IDLE;

  hr = pITaskTrigger->SetTrigger (&pTrigger);
   if (FAILED(hr))
  {
     wprintf(L"Failed calling ITaskTrigger::SetTrigger: ");
     wprintf(L"error = 0x%x\n",hr);
     CoUninitialize();
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call IPersistFile::Save to save setting to disk.
  ///////////////////////////////////////////////////////////////////
  IPersistFile *pIPersistFile;
  hr = pITask->QueryInterface(IID_IPersistFile,
                              (void **)&pIPersistFile);

  hr = pIPersistFile->Save(NULL,
                           TRUE);

  wprintf(L"The idle trigger was set and IPersistFile::Save \n");
  wprintf(L"was called to save the new trigger to disk.\n");

  ///////////////////////////////////////////////////////////////////
  // Release all resources.
  ///////////////////////////////////////////////////////////////////
  pITS->Release();
  pITask->Release();
  pIPersistFile->Release();
  CoUninitialize();
  return 0;
}


Terminating a Task Example

You can terminate a task while it is running by calling IScheduledWorkItem::Terminate.

To terminate a task if it is running

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (This example assumes that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. (Note that this examples gets the "Test Task" task.)
  3. Call ITask::GetStatus to find out if the task is running. (Note that GetStatus is an IScheduledWorkItem method inherited by ITask.)
  4. Check the status of the task and then call ITask::Terminate if the task is running. (Note that Terminate is an IScheduledWorkItem method inherited by ITask.)
For a code example using | See
C++ | C/C++ Code Example: Terminating a Task


C/C++ Code Example: Terminating a Task

This example verifies the status of a known task, terminating the task if it is running.

#include <windows.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  ITaskScheduler *pITS;
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
     return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////
  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  //Release ITaskScheduler interface.
  pITS->Release();

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::GetStatus. Note that this method is
  // inherited from IScheduledWorkItem.
  ///////////////////////////////////////////////////////////////////
  HRESULT phrStatus;

  hr = pITask->GetStatus(&phrStatus);

  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::GetStatus: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::Terminate if the status is SCHED_S_TASK_RUNNING.
  ///////////////////////////////////////////////////////////////////

  if(phrStatus==SCHED_S_TASK_RUNNING)
  {
    hr = pITask->Terminate();
    if (FAILED(hr))
    {
      wprintf(L"Failed calling ITask::Terminate: ");
      wprintf(L"error = 0x%x\n",hr);
      CoUninitialize();
      return 1;
    }
  wprintf(L"Test Task is terminated.\n");
  }
  else
  {
    wprintf(L"Test Task is not running.\n");
  }

  // Release the ITask interface.
  pITask->Release();

  CoUninitialize();
  return 0;
}


Retrieving Trigger Strings Example

You can retrieve the trigger strings of a known trigger using the IScheduledWorkItem or ITaskTrigger interface, depending on the type of object you are working with.

When working with a task object, use the methods of the IScheduledWorkItem interface to retrieve the trigger strings of a work item.

When you are working with a task trigger object, use the methods of the ITaskTrigger interface to retrieve the trigger string of the trigger.

The following example shows how to use IScheduledWorkItem::GetTriggerString to display the strings of all triggers associated with a known task.

To retrieve the trigger strings of a task

  1. Call CoInitialize to initialize the COM library and CoCreateInstance to get a Task Scheduler object. (This example assumes that the Task Scheduler service is running.)
  2. Call ITaskScheduler::Activate to get the ITask interface of the task object. (Note that this example gets the "Test Task" task.)
  3. Call ITask::GetTriggerCount to find out how many triggers are associated with a task. (Note that GetTriggerCount is an IScheduledWorkItem method inherited by ITask.)
  4. Display the trigger strings, calling ITask::GetTriggerString for each trigger associated with the task. (Note that GetTriggerString is an IScheduledWorkItem method inherited by ITask.)
  5. Release all resources. Call CoTaskMemFree to release the trigger strings and ITask::Release to release the ITask interface. (Note that Release is an IUnknown method inherited by ITask.)
For a code example using | See
C++ | Code Example: Retrieving Trigger Strings


C/C++ Code Example: Retrieving Trigger Strings

This example retrieves a trigger string for all the triggers associated with a known task.

#include <windows.h>
#include <winbase.h>
#include <initguid.h>
#include <ole2.h>
#include <mstask.h>
#include <msterr.h>
#include <wchar.h>

int main(int argc, char **argv)
{
  HRESULT hr = ERROR_SUCCESS;
  ITaskScheduler *pITS;

  ///////////////////////////////////////////////////////////////////
  // Call CoInitialize to initialize the COM library and then
  // CoCreateInstance to get the Task Scheduler object.
  ///////////////////////////////////////////////////////////////////
  hr = CoInitialize(NULL);
  if (SUCCEEDED(hr))
  {
    hr = CoCreateInstance(CLSID_CTaskScheduler,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_ITaskScheduler,
                          (void **) &pITS);
    if (FAILED(hr))
    {
      CoUninitialize();
      return 1;
    }
  }
  else
  {
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITaskScheduler::Activate to get the Task object.
  ///////////////////////////////////////////////////////////////////

  ITask *pITask;
  LPCWSTR lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);

  pITS->Release();
  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITaskScheduler::Activate: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Call ITask::TriggerCount to retrieve the number of triggers
  // associated with the task.
  ///////////////////////////////////////////////////////////////////

  WORD plTriggerCount;
  hr = pITask->GetTriggerCount (&plTriggerCount);
  if (FAILED(hr))
  {
    wprintf(L"Failed calling ITask::GetTriggerCount: ");
    wprintf(L"error = 0x%x\n",hr);
    CoUninitialize();
    return 1;
  }

  ///////////////////////////////////////////////////////////////////
  // Display the trigger stings, calling ITask::GetTriggerString for
  // each trigger associated with the task.
  ///////////////////////////////////////////////////////////////////

  wprintf(L"There are %i triggers associated with Test ");
  wprintf(L"Task.\n",plTriggerCount);
  wprintf(L"They are:\n");

  WORD CurrentTrigger=1;
  LPWSTR ppwszTrigger;

  for (CurrentTrigger=0; CurrentTrigger<plTriggerCount; CurrentTrigger++)
  {
    pITask->GetTriggerString (CurrentTrigger,
                              &ppwszTrigger);
    if (FAILED(hr))
    {
      wprintf(L"Failed calling ITask::GetTriggerString: ");
      wprintf(L"error = 0x%x\n",hr);
      CoUninitialize();
      return 1;
    }

    wprintf(L"%i) %s\n",CurrentTrigger+1, ppwszTrigger);
  }

  ///////////////////////////////////////////////////////////////////
  // Release resources.
  ///////////////////////////////////////////////////////////////////

  CoTaskMemFree(ppwszTrigger);
  pITask->Release();
  CoUninitialize();
  return 0;
}


Task Scheduler Reference

This section describes the interfaces, methods, structures, unions, and enumerators provided by the Task Scheduler API.

See | For information on
Task Scheduler Interfaces | Interfaces and methods
Task Scheduler Structures and Unions | Structures and unions
Task Scheduler Enumerated Types | Enumerators


Task Scheduler Interfaces

The interfaces and methods described in the following topics provide programmatic access to the functionality available within the Task Scheduler.

Note For information on using Task Scheduler in Microsoft® Windows® 2000, click Start, point to Settings, click Control Panel, and then double-click Scheduled Tasks. On the Help menu, click Help Topics.

Interface | Description
IEnumWorkItems | Used to enumerate the tasks in the Scheduled Tasks folder.
IProvideTaskPage | Used to access to the property sheet settings of a task.
IScheduledWorkItem | Used to manage specific work items. This interface is the base class for the ITask interface.
ITaskScheduler | Used to schedule tasks.
ITask | Used to run tasks, set and retrieve task information, and terminate tasks. This interface is a derived interface of the IScheduledWorkItem base class.
ITaskTrigger | Used to manage trigger events.

For information on | See
How the Task Scheduler interfaces work together | The Task Scheduler API


IEnumWorkItems

The IEnumWorkItems interface provides methods for enumerating the tasks in the Scheduled Tasks folder.

IEnumWorkItems is the primary interface of the enumeration object. To create the enumeration, call ITaskScheduler::Enum.

IEnumWorkItems provides the following methods, listed here in vtable order.

Method | Description
Next | Retrieves the next set of tasks in the enumeration sequence.
Skip | Skips the next set of tasks in the enumeration sequence.
Reset | Resets the enumeration sequence to the beginning.
Clone | Creates a new enumeration object in the same state as the current enumeration object: the new object points to the same place in the enumeration sequence.

For information on | See
How the Task Scheduler interfaces work together | The Task Scheduler API

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.


IEnumWorkItems::Clone

The Clone method creates a new enumeration object that contains the same enumeration state as the current one. Because the new object points to the same place in the enumeration sequence, a client can use the Clone method to record a particular point in the enumeration sequence and return to that point later.

HRESULT Clone(
  IEnumWorkItems **ppEnumWorkItems
);

Parameters

ppEnumWorkItems
[out] Pointer to a pointer to a new IEnumWorkItems interface. This pointer will point to the newly created enumeration. If the method fails, this parameter is undefined.

Return Values

Returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The argument is not valid.
E_OUTOFMEMORY | There is not enough memory available.
E_UNEXPECTED | An error occurred.

Remarks

The IEnumWorkItems interface also provides methods for retrieving sets of tasks, skipping sets of tasks, and resetting the enumeration sequence.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IEnumWorkItems, IEnumWorkItems::Next, IEnumWorkItems::Reset, IEnumWorkItems::Skip


IEnumWorkItems::Next

The Next method retrieves the next specified number of tasks in the enumeration sequence. If there are fewer than the requested number of tasks left in the sequence, all the remaining elements are retrieved.

HRESULT Next(
  ULONG celt,
  LPWSTR **rgpwszNames,
  ULONG *pceltFetched
);

Parameters

celt
[in] The number of tasks to retrieve.
rgpwszNames
[out] Pointer to an array of pointers (LPWSTR) to character strings containing the file names of the tasks returned from the enumeration sequence. These file names are taken from the Scheduled Tasks folder and have the ".job" extension.
pceltFetched
[out] Pointer to the number of tasks returned in rgpwszNames. If the celt parameter is 1, this parameter may be NULL.

Return Values

Returns one of the following values.

Value | Description
S_OK | The number of tasks retrieved equals the number requested.
S_FALSE | The number returned is less than the number requested. (Thus, there are no more tasks to enumerate.)
E_INVALIDARG | A parameter is invalid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

After processing the names returned in rgpwszNames, you must first free each character string in the array and then the array itself using CoTaskMemFree.

The IEnumWorkItems interface also provides methods for resetting the enumeration, skipping tasks, and making a copy of the current state of the enumeration.

The following code shows the declaration and calling syntax for using this method.

#define TASKS_TO_RETRIEVE    5
IEnumWorkItems *pIEnum;
LPWSTR *lpwszNames;
DWORD dwFetchedTasks = 0;
pIEnum->Next(TASKS_TO_RETRIEVE,
             &lpwszNames,
             &dwFetchedTasks);
For an example of | See
Using Next to enumerate the tasks in the Scheduled Tasks folder | Enumerating Tasks Example

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IEnumWorkItems, IEnumWorkItems::Clone, IEnumWorkItems::Reset, IEnumWorkItems::Skip


IEnumWorkItems::Reset

The Reset method resets the enumeration sequence to the beginning.

HRESULT Reset(void);

Parameters

This method has no parameters.

Return Values

Returns one of the following values.

Value | Description
S_OK | The enumeration sequence is reset to the beginning of the list.
E_OUTOFMEMORY | There is not enough available memory.

Remarks

A call to this method does not guarantee that the same set of tasks will be enumerated after the enumeration sequence is reset. Tasks may have been added to or deleted from the collection while you were enumerating the list.

The IEnumWorkItems interface also provides methods for retrieving sets of tasks, skipping sets of tasks, and making a copy of the current state of the enumeration.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IEnumWorkItems, IEnumWorkItems::Clone, IEnumWorkItems::Next, IEnumWorkItems::Skip


IEnumWorkItems::Skip

The Skip method skips the next specified number of tasks in the enumeration sequence.

HRESULT Skip(
  ULONG celt
);

Parameters

celt
[in] The number of tasks to be skipped.

Return Values

Returns one of the following values.

Value | Description
S_OK | The number of elements skipped equals celt.
S_FALSE | The number of elements remaining in the sequence is less than the value specified in celt.
E_INVALIDARG | The value of celt is less than or equal to zero.

Remarks

The IEnumWorkItems interface also provides methods for retrieving sets of tasks, resetting the enumeration sequence, and making a copy of the current state of the enumeration.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IEnumWorkItems, IEnumWorkItems::Clone, IEnumWorkItems::Next, IEnumWorkItems::Reset


IProvideTaskPage

The IProvideTaskPage interface provides access to the property sheet settings of a scheduled task.

It is the primary interface of the task object. To create a task object, call ITaskScheduler::Activate for existing tasks or ITaskScheduler::NewWorkItem for new tasks.

IProvideTaskPage provides the following method.

method | Description
GetPage | Retrieves the property sheet pages associated with a task.

For information on | See
How the Task Scheduler interfaces work together | The Task Scheduler API

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITaskScheduler::Activate, ITaskScheduler::NewWorkItem


IProvideTaskPage::GetPage

The GetPage method retrieves one or more property sheet pages associated with a task object.

HRESULT IProvideTaskPage::GetPage(
  TASKPAGE tpType,
  BOOL fPersistChanges,
  HPROPSHEETPAGE *phPage
);

Parameters

tpType
[in] One of the following TASKPAGE enumeration values that specify the page to return.
TASKPAGE_TASK
General page property.
TASKPAGE_SCHEDULE
Schedule properties for the task.
TASKPAGE_SETTINGS
Settings properties for the task.
fPersistChanges
[in] Specifies whether changes to the task object are made persistent automatically. If TRUE, the page updates the persistent task object automatically if there is a change made on release. If FALSE, the caller is responsible for making task object changes persistent by calling IPersistFile::Save on the task object.
phPage
[out] Handle to the returned property sheet page of the task object. This handle can then be used to display the page.

Return Values

Returns S_OK if the method was successful, or STG_E_NOTFILEBASEDSTORAGE if the task has not been saved to disk.

Remarks

To retrieve the IProvideTaskPage interface, call ITask::QueryInterface.

The following code shows the variable declaration and calling syntax for using this method and for calling ITask::QueryInterface.

TASKPAGE tpType = TASKPAGE_TASK;
BOOL fPersistChanges = TRUE;
HPROPSHEETPAGE phPage;
IProvideTaskPage *IProvTaskPage;
hr = pITask->QueryInterface(IID_IProvideTaskPage,
                            (void **)&pIProvTaskPage);
hr = pIProvTaskPage->GetPage(tpType,
                             fPersistChanges,
                             &phPage);
For a complete example of | See
Retrieving and displaying the general task page of a known task | Retrieving a Task Page Example

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IProvideTaskPage, TASKPAGE


IScheduledWorkItem

The IScheduledWorkItem interface provides methods for managing specific work items.

IScheduledWorkItem is the base interface for the ITask interface. All methods provided by IScheduledWorkItem are inherited by the ITask interface and are typically called through the ITask interface.

IScheduledWorkItem provides the following methods, listed here in vtable order.

Method | Description
CreateTrigger | Creates a trigger using a work item object.
DeleteTrigger | Deletes a trigger from a work item.
GetTriggerCount | Retrieves the number of triggers associated with a work item.
GetTrigger | Retrieves a trigger structure.
GetTriggerString | Retrieves a trigger string.
GetRunTimes | Retrieves the work item run times for a specified time period.
GetNextRunTime | Retrieves the next time the work item will run.
SetIdleWait | Sets the idle wait time for the work item.
GetIdleWait | Retrieves the idle wait time for the work item.
Run | Runs the work item.
Terminate | Ends the execution of the work item.
EditWorkItem | Opens the configuration properties for the work item.
GetMostRecentRunTime | Retrieves the most recent time the work item began running.
GetStatus | Retrieves the status of the work item.
GetExitCode | Retrieves the work item's last exit code.
SetComment | Sets the comment for the work item.
GetComment | Retrieves the comment for the work item.
SetCreator | Sets the creator of the work item.
GetCreator | Retrieves the creator of the work item.
SetWorkItemData | Stores application-defined data associated with the work item.
GetWorkItemData | Retrieves application-defined data associated with the work item.
SetErrorRetryCount | Not currently implemented.
GetErrorRetryCount | Not currently implemented.
SetErrorRetryInterval | Not currently implemented.
GetErrorRetryInterval | Not currently implemented.
SetFlags | Sets the flags that modify the behavior of the work item.
GetFlags | Retrieves the flags that modify the behavior of the work item.
SetAccountInformation | Sets the account name and password for the work item.
GetAccountInformation | Retrieves the account name for the work item.

For information on | See
How the Task Scheduler interfaces work together | The Task Scheduler API

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITask


IScheduledWorkItem::CreateTrigger

The CreateTrigger method creates a trigger for the work item.

HRESULT CreateTrigger(
  WORD *piNewTrigger,
  ITaskTrigger **ppTrigger
);

Parameters

piNewTrigger
[out] Pointer to the returned trigger index value of the new trigger. The trigger index for the first trigger associated with a work item is "0". See Remarks for other uses of the trigger index.
ppTrigger
[out] Pointer to a pointer to an ITaskTrigger interface. Currently tasks tasks are the only supported work item.

Return Values

The CreateTrigger method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

You use the trigger index returned by piNewTrigger when retrieving triggers, as well as when deleting triggers. However, the trigger index is not an identifier. It indicates only the new trigger's position relative to the other current triggers associated with the work item.

To set the criteria for the new trigger, call ITaskTrigger::SetTrigger.

After creating a new trigger for a work item, applications must call the IPersistFile::Save method to save the new trigger to disk.

The following code shows the variable declaration and calling syntax for using this method to create a new task trigger. Note that this method is called through the ITask interface.

  ITaskTrigger *pITaskTrigger;
  WORD piNewTrigger;
  hr = pITask->CreateTrigger(&piNewTrigger,
                             &pITaskTrigger);
For a complete example of | See
Setting the trigger criteria when creating a new trigger | Creating a New Trigger

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IPersistFile::Save, IScheduledWorkItem, IScheduledWorkItem::DeleteTrigger, IScheduledWorkItem::GetTrigger, IScheduledWorkItem::GetTriggerString, ITaskTrigger, ITaskTrigger::SetTrigger


IScheduledWorkItem::DeleteTrigger

The DeleteTrigger method deletes a trigger from a work item.

HRESULT DeleteTrigger(
  WORD iTrigger
);

Parameters

iTrigger
[in] A trigger index value that specifies the trigger to be deleted. For more information, see Remarks .

Return Values

The DeleteTrigger method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

A trigger index is created for each trigger when the trigger is created. However, it is not a unique identifier for a specific trigger. For example, if you create four triggers, they will be numbered 0 through 3. But if the second trigger is deleted, the remaining triggers will be numbered 0 through 2. Note that the index of the first trigger is always 0, and the index of the last trigger is one less than the total number of triggers for the work item (TriggerCount -1).

You can retrieve the trigger count using IScheduledWorkItem::GetTriggerCount.

To complete the deletion of the trigger, programs must call the IPersistFile::Save method after calling DeleteTrigger. Calling IPersistFile::Save saves the changes to disk.

The following code shows the variable declaration and calling syntax for using this method. This example will always delete the first trigger associated with the task. Note that this method is called through the ITask interface.

  WORD iTrigger = 0;
  hr = pITask->DeleteTrigger(iTrigger);

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

CreateTrigger, IScheduledWorkItem, IScheduledWorkItem::GetTriggerCount


IScheduledWorkItem::EditWorkItem

The EditWorkItem method displays the Task, Schedule, and settings property pages for the work item, allowing a user set the properties on those pages.

HRESULT EditWorkItem(
  HWND hParent,
  DWORD dwReserved
);

Parameters

hParent
[in] Reserved for future use. Set this parameter to NULL.
dwReserved
[in] Reserved for internal use; this must be zero.

Return Values

The EditWorkItem method returns one of the following values.

Value | Description
S_OK | The operation was successful.
STG_E_NOTFILEBASEDSTORAGE | The work item object is not persistent.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The following code shows the variable declaration and calling syntax for using this method to display property pages.

HWND hParent = NULL;
DWORD dwReserved = 0;
hr = pITask->EditWorkItem(hHandle,
                          dwReserved);
For a complete code example of | See
Editing an existing task by means of the property pages of the Task Scheduler user interface. | Editing a Work Item Using Property Pages

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem


IScheduledWorkItem::GetAccountInformation

The GetAccountInformation method retrieves the account name for the work item.

HRESULT GetAccountInformation(
  LPWSTR *ppwszAccountName
);

Parameters

ppwszAccountName
[out] Pointer to a string that contains the account name for the current work item. The empty string, L"", is returned for the local system account.

After processing the account name, be sure to call CoTaskMemFree to free the string.

Return Values

The GetAccountInformation method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.
SCHED_E_NO_SECURITY_SERVICES | Security services are available only on Windows NT/Windows 2000.

Remarks

The GetAccountInformation method is for Windows NT/Windows 2000; on Windows 95 and Windows 98, this method returns SCHED_E_NO_SECURITY_SERVICES, indicating that the Task Scheduler security services are not available. Moreover, the Task Scheduler service must be running for this method to succeed.

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

LPWSTR ppwszAccountName;
hr = pITask->GetAccountInformation(&ppwszAccountName);
For a complete example of | See
Retrieving the account information of a task | C/C++ Code Example: Retrieving Task Account Information

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::SetAccountInformation


IScheduledWorkItem::GetComment

The GetComment method retrieves the comment for the work item.

HRESULT GetComment(
  LPWSTR *ppwszComment
);

Parameters

ppwszComment
[out] Pointer to a string that contains the retrieved comment for the current work item.

Return Values

The GetComment method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

LPWSTR ppwszComment;
hr = pITask->GetComment(&ppwszComment);
For a complete example of | See
Retrieving the comment string of a task | C/C++ Code Example: Retrieving a Task Comment

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::SetComment


IScheduledWorkItem::GetCreator

The GetCreator method retrieves the name of the creator of the work item.

HRESULT GetCreator(
  LPWSTR *ppwszCreator
);

Parameters

ppwszCreator
[out] Pointer a string that contains the name of the creator of the current work item. The application that invokes GetCreator is responsible for freeing this string using the CoTaskMemFree function.

Return Values

The GetCreator method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

LPWSTR ppwszCreator;
hr = pITask->GetCreator(&ppwszCreator);
For a complete example of | See
Retrieving the name of the creator of a task | C/C++ Code Example: Retrieving the Task Creator

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::SetCreator


IScheduledWorkItem::GetErrorRetryCount

The GetErrorRetryCount method returns the number of times that the Task Scheduler will retry an operation when an error occurs. Not currently implemented.

HRESULT GetErrorRetryCount(
  WORD *pwRetryCount
);

Parameters

*pwRetryCount
[out] Pointer to a WORD that contains the number of times to retry.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See also

IScheduledWorkItem, SetErrorRetryCount


IScheduledWorkItem::GetErrorRetryInterval

The GetErrorRetryInterval method retrieves the time interval, in minutes, between Task Scheduler's attempts to run a work item if an error occurs. Not currently implemented.

HRESULT GetErrorRetryInterval(
  WORD *pwRetryInterval
);

Parameters

pwRetryInterval
[out] Pointer to a WORD value that contains the time interval between retries of the current work item.

Return Values

The GetErrorRetryInterval method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.
E_NOTIMPL | Not implemented.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See also

IScheduledWorkItem, SetErrorRetryInterval


IScheduledWorkItem::GetExitCode

The GetExitCode method retrieves the last exit code returned by the executable associated with the work item on its last run. The method also returns the exit code returned to Task Scheduler when it last attempted to run the work item.

HRESULT GetExitCode(
  DWORD *pdwExitCode
);

Parameters

pdwExitCode
[out] Pointer to a DWORD value that is set to the last exit code for the work item. This is the exit code that the work item returned when it last stopped running. If the work item has never been started, 0 is returned.

Return Values

The GetExitCode method returns the error from the last attempt to start the work item. Possible values include the following.

Value | Description
S_OK | The attempt to start the work item was successful.
SCHED_S_TASK_HAS_NOT_RUN | No attempt has ever been made to start this work item.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

This method returns the following two pieces of information:

  • the error or exit code returned by the executable that's being scheduled is returned to pdwExitCode.
  • the GetExitCode method itself returns the error code that the Task Scheduler received when it tried to start the job.

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

DWORD pdwExitCode;
hr = pITask->GetExitCode(&pdwExitCode);
For a complete example of | See
Retrieving the creator of a task | C/C++ Code Example: Retrieving the Task Creator

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem


IScheduledWorkItem::GetFlags

The GetFlags method returns the flags that modify the behavior of any type of work item.

HRESULT GetFlags(
  DWORD *pdwFlags
);

Parameters

pdwFlags
[out] Pointer to a DWORD that contains the flags for the work item. For a list of these flags, see SetFlags.

Return Values

The GetFlags method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

This method is used to get those flags used by any type of scheduled work item. In contrast, ITask::GetTaskFlags is used only to get flags used by scheduled tasks.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::SetFlags, ITask::GetTaskFlags


IScheduledWorkItem::GetIdleWait

The GetIdleWait method retrieves the idle wait time for the work item.

HRESULT GetIdleWait(
  WORD *pwIdleMinutes,
  WORD *pwDeadlineMinutes
);

Parameters

pwIdleMinutes
[out] Pointer to a WORD that contains the idle wait time for the current work item, in minutes.
pwDeadlineMinutes
[out] Pointer to a WORD that specifies the maximum number of minutes that Task Scheduler will wait for the idle-time period returned in pwIdleMinutes.

Return Values

The GetIdleWait method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.

Remarks

The idle time returned here is used in conjunction with idle triggers and idle conditions. Idle triggers are event-based triggers that are not associated with a scheduled time. Idle conditions are associated with the scheduled start time for the task.

Idle triggers are specified by setting the TASK_TRIGGER_TYPE member of the TASK_TRIGGER structure to the value TASK_EVENT_TRIGGER_ON_IDLE. The idle trigger is fired when the system becomes idle for the amount of time returned in pwIdleMinutes.

You can set idle conditions by calling IScheduledWorkItem::SetFlags. If the TASK_FLAG_START_ONLY_IF_IDLE flag is set, the work item runs at its scheduled time only if the system becomes idle for the amount of time returned in pwIdleMinutes. The Task Scheduler service will wait up to pwDeadlineMinutes past the scheduled start time to see if the system becomes idle.

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

WORD pwIdleMinutes;
WORD pwDeadlineMinutes;
hr = pITask->GetIdleWait(&pwIdleMinutes,
                         &pwDeadlineMinutes);
For a complete example of | See
Retrieving the idle wait time of a task | C/C++ Code Example: Retrieving Task Idle-wait Time

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::SetIdleWait


IScheduledWorkItem::GetMostRecentRunTime

The GetMostRecentRunTime method retrieves the most recent time the work item began running.

HRESULT GetMostRecentRunTime(
  SYSTEMTIME *pstLastRun
);

Parameters

pstLastRun
[out] Pointer to a SYSTEMTIME structure that contains the most recent time the current work item ran.

Return Values

The GetMostRecentRunTime method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.
SCHED_S_TASK_HAS_NOT_RUN | The work item has never run.

Remarks

The following code shows the variable declaration and calling syntax for calling this method. Note that this method is called through the ITask interface.

SYSTEMTIME pstLastRun;
hr = pITask->GetMostRecentRunTime(&pstLastRun);
For a complete example of | See
Retrieving the last time a task ran | C/C++ Code Example: Retrieving the Task MostRecentRun Time

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, GetNextRunTime


IScheduledWorkItem::GetNextRunTime

The GetNextRunTime method retrieves the next time the work item will run.

HRESULT GetNextRunTime(
  SYSTEMTIME *pstNextRun
);

Parameters

pstNextRun
[out] Pointer to a SYSTEMTIME structure that contains the next time the work item will run.

Return Values

The GetNextRunTime method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

SYSTEMTIME pstNextRun;
hr = pITask->GetNextRunTime(&pstNextRun);
For a complete example of | See
Retrieving the next time a task is scheduled to run | C/C++ Code Example: Retrieving the Task NextRun Time

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem


IScheduledWorkItem::GetRunTimes

The GetRunTimes method retrieves the work item run times for a specified time period.

HRESULT GetRunTimes(
  const LPSYSTEMTIME pstBegin,
  const LPSYSTEMTIME pstEnd,
  WORD *pCount,
  LPSYSTEMTIME *rgstTaskTimes
);

Parameters

pstBegin
[in] Pointer to a SYSTEMTIME structure that contains the starting time of the time period to check. This value is inclusive.
pstEnd
[in] Pointer to a SYSTEMTIME structure that contains the ending time of the time period to check. This value is exclusive. If NULL is passed for this value, the end time is infinite.
pCount
[in, out] Pointer to a WORD value that specifies the number of run times to retrieve.

On input, this parameter contains the number of run times being requested. This can be a number between 1 and TASK_MAX_RUN_TIMES.

On output, this parameter contains the number of run times actually retrieved.

rgstTaskTimes
[out] Pointer to an array of SYSTEMTIME structures. On return, this array contains pCount run times. You must free this array by a calling the CoTaskMemFree function.

Return Values

The GetRunTimes method returns one of the following values.

Value | Description
S_OK | The requested number of run times was retrieved.
S_FALSE | The method succeeded, but fewer than the requested number of run times were retrieved. The number of run times retrieved is contained in the value pointed to by pCount. If the number of run times retrieved is zero, there are also no event-based triggers that can cause the work item to be executed during the specified time period.
SCHED_S_EVENT_TRIGGER | No run times exist for the specified time period, but event-based triggers exist that might cause the work item to run during the specified time period.
SCHED_S_TASK_NO_VALID_TRIGGERS | The work item is enabled but has no valid triggers.
SCHED_S_TASK_DISABLED | The work item is disabled.
E_INVALIDARG | One or more of the arguments are invalid.
E_OUTOFMEMORY | There is insufficient memory to compute the result.

Remarks

The following code shows the variable declaration and calling syntax for calling this method. In this example, GetSystemTime is called to get the beginning time. Note that this method is called through the ITask interface.

SYSTEMTIME stNow;
LPSYSTEMTIME pstListOfTimes;
LPSYSTEMTIME pstListBegin;
WORD wCountOfRuns = 5;

GetSystemTime(&stNow);
hr = pITask->GetRunTimes(&stNow,
                         NULL,
                         &wCountOfRuns,
                         &pstListBegin);
For a complete example of | See
Retrieving the run times of a task | C/C++ Code Example: Retrieving Task Run Times

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem


IScheduledWorkItem::GetStatus

The GetStatus method retrieves the status of the work item.

HRESULT GetStatus(
  HRESULT *phrStatus
);

Parameters

phrStatus
[out] Pointer to an HRESULT value that contains one of the following values on return.
SCHED_S_TASK_READY
The work item is ready to run at its next scheduled time.
SCHED_S_TASK_RUNNING
The work item is currently running.
SCHED_S_TASK_NOT_SCHEDULED
One or more of the properties that are needed to run this work item on a schedule have not been set.

Return Values

The GetStatus method returns one of the following values.

Value | Description
S_OK | The operation was successful. The request was sent. For more information, see Remarks.
E_INVALIDARG | The arguments are not valid.

Remarks

The methods of the IScheduledWorkItem interface are inherited by the ITask interface. Consequently, GetStatus is typically called through the ITask interface.

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

  HRESULT hrStatus;
  hr = pITask->GetStatus(&hrStatus);
For a complete example of | See
Retrieving the status of a task | C/C++ Code Example: Retrieving Task Status
Retrieving the task status as part of terminating the task | Terminating a Task Example

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, ITask


IScheduledWorkItem::GetTrigger

The GetTrigger method retrieves a task trigger.

HRESULT GetTrigger(
  WORD iTrigger,
  ITaskTrigger **ppTrigger
);

Parameters

iTrigger
[in] Specifies which trigger to retrieve.
ppTrigger
[out] Pointer to a pointer to an ITaskTrigger interface for the retrieved trigger.

Return Values

The GetTrigger method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, ITaskTrigger


IScheduledWorkItem::GetTriggerCount

The GetTriggerCount method retrieves the number of triggers for the current work item.

HRESULT GetTriggerCount(
  WORD *plCount
);

Parameters

plCount
[out] Pointer to a WORD that will contain the number of triggers associated with the work item.

Return Values

The GetTriggerCount method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The following code shows the variable declaration and calling syntax for this method. Note that this code calls the GetTriggerCount method through the ITask interface.

WORD plTriggerCount;
hr = pITask->GetTriggerCount(&plTriggerCount);
For a complete example of | See
Getting the trigger count to retrieve the trigger strings of a task. | Retrieving Trigger Strings Example

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, ITask


IScheduledWorkItem::GetTriggerString

The GetTriggerString method retrieves a string that describes the work item trigger.

HRESULT GetTriggerString(
  WORD iTrigger,
  LPWSTR *ppwszTrigger
);

Parameters

iTrigger
[in] Specifies the index of the trigger to be retrieved. The first trigger is always referenced by 0. For more information, see Remarks.
ppwszTrigger
[out] Pointer to a string that contains the retrieved trigger description. Note that this string must be release by a call to CoTaskMemFree after the string is no longer needed.

Return Values

The GetTriggerString method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

A trigger index is not an identifier. It only indicates the trigger's position relative to the current triggers associated with the work item. For example, if you create four triggers, they will be numbered 0 through 3. But if the second trigger is deleted, the remaining triggers will be numbered 0 through 2. Note that the index of the first trigger is always 0, and the index of the last trigger is one less than the total number of triggers for the work item (TriggerCount -1).

You can retrieve the trigger count using IScheduledWorkItem::GetTriggerCount.

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

WORD iTrigger;
LPWSTR ppwszTrigger;
hr = pITask->GetTriggerCount(iTrigger,
                             &ppwszTrigger);
CoTaskMemFree(ppwszTrigger);
For a complete example of | See
Retrieving the trigger string of all triggers associated with a task. | Retrieving Trigger Strings Example

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, ITask


IScheduledWorkItem::GetWorkItemData

The GetWorkItemData method retrieves application-defined data associated with the work item.

HRESULT GetWorkItemData(
  WORD *pcBytes,
  BYTE **ppBytes
);

Parameters

pcBytes
Pointer to the number of bytes copied.
ppBytes
Pointer to a pointer to a BYTE that contains user-defined data for the current work item. The method that invokes GetWorkItemData is responsible for freeing this memory by using CoTaskMemFree.

Return Values

The GetWorkItemData method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

Retrieving the data of a work item does not affect the operation of the work item in any way.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

CoTaskMemFree, IScheduledWorkItem, SetWorkItemData


IScheduledWorkItem::Run

The Run method sends a request to the Task Scheduler service to run the work item.

HRESULT Run(void);

Parameters

This method has no parameters.

Return Values

The Run method returns one of the following values.

Value | Description
S_OK | The operation was successful. The request was sent. For more information, see Remarks.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

Run is an asynchronous operation. A return code of S_OK means that the request to run the work item has been made; it does not mean that the work item has started running. There may be a delay of a few seconds after Run returns before the work item actually starts running.

To determine whether the work item is running, call IScheduledWorkItem::GetStatus.

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

ITask  pITask;
hr = pITask->Run();
For a complete example of | See
Starting a task | Starting a Task Example

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::GetStatus, ITask


IScheduledWorkItem::SetAccountInformation

The SetAccountInformation method sets the account name and password used to run the work item.

HRESULT SetAccountInformation(
  LPCWSTR pwszAccountName,
  LPCWSTR pwszPassword
);

Parameters

pwszAccountName
[in] String that contains the name of the user account in which the work item will run. The empty string, L"", may be used to specify the local system account. For more information, see Remarks.
pwszPassword
[in] String that contains the password for the account specified in pwszAccountName.

Set this parameter to NULL if the local account is specified or, optionally, for an account other than local system if the TASK_FLAG_RUN_ONLY_IF_LOGGED_ON flag was not passed to IScheduledWorkItem::SetFlags. (The TASK_FLAG_RUN_ONLY_IF_LOGGED_ON flag is provided so that applications can schedule tasks in their own accounts without knowing their own accounts' passwords.) For more information, see Remarks.

Return Values

The SetAccountInformation method returns one of the following values. Note that errors from this call may also be returned by the subsequent call to IPersistFile::Save.

Value | Description
S_OK | The operation was successful.
E_ACCESSDENIED | The caller does not have permission to perform the operation. For more information, see Remarks.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.
SCHED_E_NO_SECURITY_SERVICES | Security services are available only on Windows NT/Windows 2000.
SCHED_E_UNSUPPORTED_ACCOUNT_OPTION | The pwszPassword parameter was set to NULL, but the TASK_FLAG_RUN_ONLY_IF_LOGGED_ON flag was not set.

Remarks

This method is for Windows NT/Windows 2000 systems only; on Windows 95 and Windows 98 systems, this method returns SCHED_E_NO_SECURITY_SERVICES, indicating that the Task Scheduler security services are not available.

If pwszAccountName specifies the local account, the caller must be an administrator on the local computer or an application running in the local system account. If not, this method will fail.

The password specified in pwszPassword is used to log on to the account when the work item is run. An incorrect password will result in an error when the work item is run.

Programs must call the IPersistFile::Save method after calling SetAccountInformation to update the account information. Note that errors can be returned by the initial call to SetAccountInformation or the subsequent call to IPersistFile::Save.

The Task Scheduler service must be running for this call to succeed. (SetAccountInformation results in a remote procedure call (RPC) to the Task Scheduler service, but the RPC call is not made until IPersistFile::Save is called.)

The E_ACCESSDENIED return code is returned under the following conditions:

  • The caller does not have write access to the file representing the scheduled work item.
  • The local account was specified (pwszAccountName was set to L""), but the caller is neither an administrator on the local computer nor an application running in the local system account.
  • A NULL password was specified in pwszPassword, but the caller is neither an administrator on the local computer, nor running in the local system account
  • The application is running under a different user name than the user named specified in the pwszAccountName parameter.

After setting the account information for a work item, be sure to call IPersistFile::Save to save the modified work item object to disk.

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

LPCWSTR pwszAccountName = L"myAccount";
LPCWSTR pwszPassword = L"myPassword";
hr = pITask->SetAccountInformation(pwszAccountName,
                                     pwszPassword);
For a complete code example of | See
Setting the account information of a task | C/C++ Code Example: Setting Task Account Information

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::GetAccountInformation, IScheduledWorkItem::SetFlags


IScheduledWorkItem::SetComment

The SetComment method sets the comment for the work item.

HRESULT SetComment(
  LPCWSTR pwszComment
);

Parameters

pwszComment
[in] A string that specifies the comment for the current work item.

Return Values

The SetComment method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

After setting the comment of a work item, be sure to call IPersistFile::Save to save the modified work item object to disk.

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

  LPCWSTR pwszComment = L"This task is used to test the Task Scheduler APIs.";
  hr = pITask->SetComment(pwszComment);
For a complete code example of | See
Setting the comment of a task | C/C++ Code Example: Setting Task Comment

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::GetComment, ITask


IScheduledWorkItem::SetCreator

The SetCreator method sets the name of the work item's creator.

HRESULT SetCreator(
  LPCWSTR pwszCreator
);

Parameters

pwszCreator
String that contains the name of the work item's creator.

Return Values

The SetCreator method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

Programs must call the IPersistFile::Save method after calling SetCreator to update the creator.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::GetCreator


IScheduledWorkItem::SetErrorRetryCount

The SetErrorRetryCount method sets the number of times Task Scheduler will try to run the work item again if an error occurs. Not currently implemented.

HRESULT SetErrorRetryCount(
  WORD wRetryCount
);

Parameters

wRetryCount
Specifies the number of error retries for the current work item.

Return Values

The SetErrorRetryCount method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.
E_NOTIMPL | Not implemented.

Remarks

Programs must call the IPersistFile::Save method after calling SetErrorRetryCount to update the error retry count.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::GetErrorRetryCount


IScheduledWorkItem::SetErrorRetryInterval

The SetErrorRetryInterval method sets the time interval, in minutes, between Task Scheduler's attempts to run a work item after an error occurs. Not currently implemented.

HRESULT SetErrorRetryInterval(
  WORD wRetryInterval
);

Parameters

wRetryInterval
Specifies the interval between error retries for the current work item, in minutes.

Return Values

The SetErrorRetryInterval method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.
E_NOTIMPL | Not implemented.

Remarks

Programs must call the IPersistFile::Save method after calling SetErrorRetryInterval to update the error retry interval.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::GetErrorRetryInterval


IScheduledWorkItem::SetFlags

The SetFlags method sets the flags that modify the behavior of any type of work item.

HRESULT SetFlags(
  DWORD dwFlags
);

Parameters

dwFlags
Contains a combination of one or more of the following flags:
TASK_FLAG_INTERACTIVE
This flag is used when converting Windows NT AT service jobs into work items. The Windows NT AT service job refers to At.exe, the Windows NT command-line utility used for creating jobs for the Windows NT Schedule service. The Task Scheduler service replaces the Schedule service and is backwards compatible with it. The conversion occurs when the Task Scheduler is installed on Windows NT/Windows 2000 — for example, if you install Internet Explorer 4.0, or upgrade to Windows 2000. During the setup process, the Task Scheduler installation code searches the registry for jobs created for the AT service and creates work items that will accomplish the same operation.

For such converted jobs, the interactive flag is set if the work item is intended to be displayed to the user. When this flag is not set, no work items are displayed in the Tasks folder, and no user interface associated with the work item is presented to the user when the work item is executed.

TASK_FLAG_DELETE_WHEN_DONE
The work item will be deleted when there are no more scheduled run times.
TASK_FLAG_DISABLED
The work item is disabled. This is useful to temporarily prevent a work item from running at the scheduled time(s).
TASK_FLAG_HIDDEN
The work item is hidden. When the work item begins execution, it runs in a hidden window.
TASK_FLAG_RUN_ONLY_IF_LOGGED_ON
The work item runs only if the user specified in IScheduledWorkItem::SetAccountInformation is logged on interactively. This flag has no effect on work items set to run in the local account.
TASK_FLAG_START_ONLY_IF_IDLE
The work item begins only if the computer is not in use at the scheduled start time. Windows 95 only.
TASK_FLAG_SYSTEM_REQUIRED
TASK_FLAG_KILL_ON_IDLE_END
The work item terminates if the computer makes an idle to non-idle transition while the work item is running. The computer is not considered idle until the IdleWait triggers' time elapses with no user input. Windows 95 only. For information regarding idle triggers, see Idle Trigger.
TASK_FLAG_RESTART_ON_IDLE_RESUME
The work item starts again if the computer makes a non-idle to idle transition before all the work item's task_triggers elapse. (Use this flag in conjunction with TASK_FLAG_KILL_ON_IDLE_END.) Windows 95 only.
TASK_FLAG_DONT_START_IF_ON_BATTERIES
The work item does not start if its target computer is running on battery power. Windows 95 only.
TASK_FLAG_KILL_IF_GOING_ON_BATTERIES
The work item ends, and the associated application quits if the work item's target computer switches to battery power. Windows 95 only.
TASK_FLAG_RUN_IF_CONNECTED_TO_INTERNET
The work item runs only if there is currently a valid Internet connection. Note This feature is currently not implemented.

Return Values

The SetFlags method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

Programs must call the IPersistFile::Save method after calling SetFlags to update the flags.

This method is used to set those flags used by any type of scheduled work item. In contrast, ITask::SetTaskFlags is used only to set flags used by scheduled tasks.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::GetFlags, IScheduledWorkItem::SetAccountInformation


IScheduledWorkItem::SetIdleWait

The SetIdleWait method sets the minutes that the system must be idle before the work item can run.

HRESULT SetIdleWait(
  WORD wIdleMinutes,
  WORD wDeadlineMinutes
);

Parameters

wIdleMinutes
[in] Specifies how long, in minutes, the system must remain idle before the work item can run.
wDeadlineMinutes
[in] Specifies the maximum number of minutes that Task Scheduler will wait for the idle-time period returned in pwIdleMinutes.

Return Values

The SetIdleWait method returns S_OK.

Remarks

The idle time specified here is used in conjunction with idle triggers and idle conditions. Idle triggers are event based triggers that are not associated with a scheduled time. Idle conditions, in contrast, are associated with the scheduled start time for the task.

You specify idle triggers by setting the TASK_TRIGGER_TYPE member of the TASK_TRIGGER to TASK_EVENT_TRIGGER_ON_IDLE. The idle trigger is fired when the system becomes idle for the amount of time specified by wIdleMinutes.

You set idle conditions by calling IScheduledWorkItem::SetFlags. If the TASK_FLAG_START_ONLY_IF_IDLE flag is set, the work item runs at its scheduled time only if the system becomes idle for the amount of time specified by wIdleMinutes. The Task Scheduler service will wait up to the number of minutes specified in wDeadlineMinutes past the scheduled start time to see if the system becomes idle.

Applications must call the IPersistFile::Save method after calling SetIdleWait to update the idle wait interval.

The following code shows the variable declaration and calling syntax for using this method with an idle trigger. Note that this method is called through the ITask interface.

  WORD wIdleMinutes = 3
  WORD wDeadlineMinutes = 5;
  hr = pITask->SetIdleWait(wIdleMinutes,
                           wDeadlineMinutes);
For a complete example of | See
Setting the idle wait time when creating an idle trigger | Creating an Idle Trigger Example

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::GetIdleWait


IScheduledWorkItem::SetWorkItemData

The SetWorkItemData method stores application-defined data associated with the work item.

HRESULT SetWorkItemData(
  WORD cBytes,
  BYTE rgbData[]
);

Parameters

cBytes
Specifies the number of bytes in the data buffer. The caller allocates and frees this memory.
rgbData
Data to copy.

Return Values

The SetWorkItemData method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

You can retrieve data by calling IScheduledWorkItem::GetWorkItemData.

Programs must call the IPersistFile::Save method after calling SetWorkItemData to update the work item data.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, IScheduledWorkItem::GetWorkItemData


IScheduledWorkItem::Terminate

The Terminate method ends the execution of the work item.

HRESULT Terminate(void);

Parameters

This method has no parameters.

Return Values

The Terminate method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The Terminate method operates asynchronously. It does not wait for the task to terminate before returning a return value.

If the WM_CLOSE message cannot be sent (for example, the application has no windows) or the application has not exited within three minutes of the receiving WM_CLOSE, the Task Scheduler terminates the application using TerminateProcess.

The following code shows the variable declaration and calling syntax for this method. Note that this method is called through the ITask interface.

  hr = pITask->Terminate();
For a complete example of | See
Retrieving the task status and terminating a task | Terminating a Task Example

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, ITask


ITask

The ITask interface is used to run tasks and to set and retrieve task properties. It is derived from the IScheduledWorkItem interface and inherits all the methods of that interface.

ITask is the primary interface of the task trigger object. To create a task object, call ITaskScheduler::Activate for existing tasks or ITaskScheduler::NewWorkItem for new tasks.

ITask provides the following methods, listed here in vtable order. (Methods inherited from IScheduledWorkItem are not listed here.)

IUnkown Methods | Description
QueryInterface | Gets pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.

IPersistFile Methods | Description
IsDirty | Checks an object for changes since it was last saved to its current file.
Load | Opens the specified file and initializes an object from the file contents.
Save | Saves the object into the specified file.
SaveCompleted | Notifies the object that it can revert from NoScribble mode to Normal mode.
GetCurFile | Gets the current name of the file associated with the object.

ITask Methods | Description
SetApplicationName | Assigns a specific application to the current task.
GetApplicationName | Retrieves the name of the application that the task is associated with.
SetParameters | Sets the command-line parameters for the task.
GetParameters | Retrieves the command-line parameters of a task.
SetWorkingDirectory | Sets the working directory for the task.
GetWorkingDirectory | Retrieves the working directory of the task.
SetPriority | Sets the priority for the task.
GetPriority | Retrieves the priority for the task.
SetTaskFlags | Sets the flags that modify the behavior of the task.
GetTaskFlags | Returns the flags used to modify the behavior of the task.
SetMaxRunTime | Sets the maximum length of time the task can run.
GetMaxRunTime | Retrieves the maximum length of time the task can run.

For information on | See
How all the interfaces of the Task Scheduler API work together | The Task Scheduler API

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, ITaskScheduler::Activate, ITaskScheduler::NewWorkItem


ITask::GetApplicationName

The GetApplicationName method retrieves the name of the application that the task is associated with.

HRESULT GetApplicationName(
  LPWSTR *ppwszApplicationName
);

Parameters

ppwszApplicationName
[out] Pointer to a string that contains the name of the application the current task is associated with. After processing this name, call CoTaskMemFree to free resources.

Return Values

The GetApplicationName method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The following code shows the variable declaration and calling syntax for this method.

  ITask *pITask;
  LPWSTR lpwszApplicationName;
  hr = pITask->GetApplicationName(&lpwszApplicationName);
  //Process name.
  CoTaskMemFree(lpwszApplicationName);
For a complete example of | See
Retrieving the name of the application associated with a task | C/C++ Code Example: Retrieving the Task Application Name
Retrieving other task properties | Retrieving Task Property Examples

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITask, ITask::SetApplicationName, SetParameters


ITask::GetMaxRunTime

The GetMaxRunTime method retrieves the maximum length of time, in milliseconds, the task can run before terminating.

HRESULT GetMaxRunTime(
  DWORD *pdwMaxRunTime
);

Parameters

pdwMaxRunTime
[out] Pointer to a DWORD that contains the maximum run time of the current task.

If the maximum run time is reached during the execution of a task, the Task Scheduler first sends a WM_CLOSE message to the associated application. If the application doesn't exit within three minutes, TerminateProcess is run.

Return Values

The GetMaxRunTime method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The following code shows the variable declaration and calling syntax for this method.

  ITask *pITask;
  DWORD pdwRunTime;
  hr = pITask->GetMaxRunTime(&pdwRunTime);
  //Process max run time value
For a complete example of | See
Retrieving the maximum run time of a task | C/C++ Code Example: Retrieving the Task MaxRunTime
Retrieving other task properties | Retrieving Task Property Examples

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITask, SetMaxRunTime


ITask::GetParameters

The GetParameters method retrieves the task's command-line parameters.

HRESULT GetParameters(
  LPWSTR *ppwszParameters
);

Parameters

ppwszParameters
[out] Pointer to string that contains the command line parameters for the task. The method that invokes GetParameters is responsible for freeing this string using the CoTaskMemFree function.

Return Values

The GetParameters method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.0

Remarks

The following code shows the variable declaration and calling syntax for this method.

  ITask *pITask;
  LPWSTR lpwszParameters;
  hr = pITask->GetParameters(&lpwszParameters);
  //Process max run time value.
  CoTaskMemFree(lpwszParameters);
For a complete example of | See
Retrieving the parameter string of a task | C/C++ Code Example: Retrieving Task Parameters
Retrieving other task properties | Retrieving Task Property Examples

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITask, SetParameters


ITask::GetPriority

The GetPriority method retrieves the priority for the task.

HRESULT GetPriority(
  DWORD *pdwPriority
);

Parameters

pdwPriority
[out] Pointer to a DWORD that contains the priority for the current task. The priority value determines the frequency and length of the time slices for a process. This applies only to Windows NT/Windows 2000 and has no effect in Windows 95. It is taken from the CreateProcess priority class and can be one of the following flags (in descending order of thread scheduling priority):
  • REALTIME_PRIORITY_CLASS
  • HIGH_PRIORITY_CLASS
  • NORMAL_PRIORITY_CLASS
  • IDLE_PRIORITY_CLASS

Return Values

The GetPriority method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The following code shows the variable declaration and calling syntax for this method.

ITask *pITask;
DWORD pdwPriority;
hr = pITask->GetPriority(&pdwPriority);
For a complete example of | See
Retrieve the priority level of a task | C/C++ Code Example: Retrieving Task Priority
Retrieving other task properties | Retrieving Task Property Examples

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITask, SetPriority


ITask::GetTaskFlags

The GetTaskFlags method returns the flags that modify the behavior of a task.

HRESULT GetTaskFlags(
  DWORD *pdwFlags
);

Parameters

pdwFlags
[out] Currently there are no defined flags for scheduled tasks.

Return Values

The GetTaskFlags method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

This method is designed to get the flags that only apply to scheduled tasks. In contrast, IScheduledWorkItem::GetFlags is used to get the flags that apply to all types of scheduled work item.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem::GetFlags, ITask, ITask::SetTaskFlags


ITask::GetWorkingDirectory

The GetWorkingDirectory method retrieves the task's working directory.

HRESULT GetWorkingDirectory(
  LPWSTR *ppwszWorkingDirectory
);

Parameters

ppwszWorkingDirectory
[in] Pointer to a string that contains the task's working directory. The application that invokes GetWorkingDirectory is responsible for freeing this string using the CoTaskMemFree function.

Return Values

The GetWorkingDirectory method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The following code shows the variable declaration and calling syntax for this method.

  ITask *pITask;
  LPWSTR lpwszWorkDir;
  hr = pITask->GetWorkingDirectory(&lpwszWorkDir);
  //Process working directory.
  CoTaskMemFree(lpwszWorkDir);
For a complete example of | See
Retrieving the working directory associated with a task | C/C++ Code Example: Retrieving the task Working Directory
Retrieving other task properties | Retrieving Task Property Examples

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITask, SetWorkingDirectory


ITask::SetApplicationName

The SetApplicationName method assigns a specific application to the current task.

HRESULT SetApplicationName(
  LPCWSTR pwszApplicationName
);

Parameters

pwszApplicationName
[in] String that contains a name of the application that will be associated with the task. Use a zero-length string to clear the application name.

Return Values

The SetApplicationName method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

If you do not specify a path for the application, the Task Scheduler searches the environment path to find the correct path. If the application name specifies a program, the name should use the .exe extension to ensure that the Task Scheduler user interface properly displays the application's icon.

After calling SetApplicationName, make sure you call IPersistFile::Save to save the modified task to disk.

The following code shows the variable declaration and calling syntax for this method. Note that this code specifies Microsoft Notepad.

LPCWSTR pwszApplicationName = L"C:\\WINNT40\\notepad.exe";
hr = pITask->SetApplicationName(pwszApplicationName);
For a complete code example of | See
Setting the application name | C/C++ Code Example: Setting Application Name

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

GetApplicationName, ITask


ITask::SetMaxRunTime

The SetMaxRunTime method sets the maximum time the task can run, in milliseconds, before terminating.

HRESULT SetMaxRunTime(
  DWORD dwMaxRunTime
);

Parameters

dwMaxRunTime
[in] A DWORD value that specifies the maximum run time (in milliseconds), for the task. This parameter may be set to INFINITE to specify an unlimited time.

Return Values

The SetMaxRunTime method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

When the maximum run time is exceeded, the Task Scheduler attempts to terminate the application associated with the task. If a WM_CLOSE message cannot be sent (for example, the application has no windows) or the application has not exited within three minutes of the receiving WM_CLOSE, the Task Scheduler terminates the application using TerminateProcess.

After setting the maximum run time, be sure to call IPersistFile::Save to save the modified task object to disk.

The following code shows the variable declaration and calling syntax for this method. Note that this code sets the maximum run time to 5 minutes.

DWORD dwMaxRunTime = (1000*60*5);
hr = pITask->SetMaxRunTime(dwMaxRunTime);
For a complete code example of | See
Setting the maximum run time | C/C++ Code Example: Setting MaxRunTime

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IGetMaxRunTime, ITask


ITask::SetParameters

The SetParameters method sets the command-line parameters for the task.

HRESULT SetParameters(
  LPCWSTR pwszParameters
);

Parameters

pwszParameters
[in] String that contains task parameters. These parameters are passed as command-line arguments to the application the task will run. To clear the command-line parameter property, set pwszParameters to L"".

Return Values

The SetParameters method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

If the task has an application associated with it, the task parameters set by this method are ignored.

After setting the parameters of the task, be sure to call IPersistFile::Save to save the modified task object to disk.

The following code shows the variable declaration and calling syntax for this method. Note that this code clears the parameter of the task.

LPCWSTR pwszParameters = L"";
hr = pITask->SetParameters(pwszParameters);
For a complete code example of | See
Setting parameters | C/C++ Code Example: Setting Task Parameteres

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITask


ITask::SetPriority

The SetPriority method sets the priority for the task.

HRESULT SetPriority(
  DWORD dwPriority
);

Parameters

dwPriority
[in] A DWORD that specifies the priority for the current task. The priority of a task determines the frequency and length of the time slices for a process. This applies only to Windows NT/Windows 2000 and has no effect in Windows 95. These values are taken from the CreateProcess priority class and can be one of following flags (in descending order of thread scheduling priority):
  • REALTIME_PRIORITY_CLASS
  • HIGH_PRIORITY_CLASS
  • NORMAL_PRIORITY_CLASS
  • IDLE_PRIORITY_CLASS

Return Values

The SetPriority method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.

Remarks

After setting the priority of a task, be sure to call IPersistFile::Save to save the modified task object to disk.

The following code shows the variable declaration and calling syntax for this method. Note that this code sets the priority level to HIGH_PRIORITY_CLASS.

DWORD dwPriority = HIGH_PRIORITY_CLASS;
hr = pITask->SetPriority(dwPriority);
For a complete code example of | See
Setting the priority of a task | C/C++ Code Example: Setting Task Priority

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

GetPriority, ITask


ITask::SetTaskFlags

The SetTaskFlags method sets the flags that modify the behavior of a scheduled task.

HRESULT SetTaskFlags(
  DWORD dwFlags
);

Parameters

dwFlags
[in] Currently there are no flags defined for scheduled tasks.

Return Values

The SetTaskFlags method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

Applications must call the IPersistFile::Save method after calling SetTaskFlags to update the task flags.

This method is designed to set the flags that only apply to scheduled tasks. In contrast, IScheduledWorkItem::SetFlags is used to set the flags that apply to all types of scheduled work item.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

GetTaskFlags, IScheduledWorkItem::SetFlags, ITask


ITask::SetWorkingDirectory

The SetWorkingDirectory method sets the working directory for the task.

HRESULT SetWorkingDirectory(
  LPCWSTR pwszWorkingDirectory
);

Parameters

pwszWorkingDirectory
[in] String that contains a directory path to the working directory for the task.

The application starts with this directory as the current working directory. To clear the directory, set pwszWorkingDirectory to L"". If the working directory is set to L"", when the application is run, the current directory will be the directory in which the task scheduler service executable, Mstask.exe, resides.

Return Values

The SetWorkingDirectory method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

After setting the working directory of a task, be sure to call IPersistFile::Save to save the modified task object to disk.

The following code shows the variable declaration and calling syntax for this method. Note that this code sets the working directory to "C:/Temp".

LPCWSTR pwszWorkingDirectory = L"C://Temp";
hr = pITask->SetWorkingDirectory(pwszWorkingDirectory);
For a complete code example of | See
Setting the working directory of a task of a task | C/C++ Code Example: Setting Working Directory

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

GetWorkingDirectory, ITask


ITaskScheduler

The ITaskScheduler interface provides methods for scheduling tasks.

It is the primary interface of the task scheduler object. To create a task scheduler object, call CoCreateInstance.

ITaskScheduler provides the following methods, listed here in vtable order.

IUnkown Methods | Description
QueryInterface | Gets pointers to supported interfaces
AddRef | Increments the reference count.
Release | Decrements the reference count.

ITaskScheduler Methods | Description
SetTargetComputer | Selects the computer that the ITaskScheduler interface operates on.
GetTargetComputer | Returns the name of the computer on which ITaskScheduler is currently targeted.
Enum | Retrieves a pointer to an OLE enumerator object that enumerates the tasks in the current task folder.
Activate | Returns an active interface to the specified task.
Delete | Deletes a task.
NewWorkItem | Allocates space for a new task and retrieves its address.
AddWorkItem | Adds a task to the schedule of tasks.
IsOfType | Checks the object type.

For information on | See
How all the interfaces of the Task Scheduler API work together | The Task Scheduler API

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.


ITaskScheduler::Activate

The Activate method returns an active interface for a specified work item.

HRESULT Activate(
  LPCWSTR pwszName,
  REFIID riid,
  IUnknown **ppunk
);

Parameters

pwszName
[in] String that specifies the name of the work item to activate.
riid
[in] Identifies the interface being requested. The only interface supported at this time, ITask, has the identifier IID_ITask.
ppunk
[out] Pointer to an interface pointer that receives the address of the requested interface.

Return Values

The Activate method returns one of the following values.

Value | Description
S_OK | The method was successful.
SCHED_E_UNKNOWN_OBJECT_VERSION | The task object version is either unsupported or invalid.
E_INVALIDARG | The pwszName parameter is not valid.
E_OUTOFMEMORY | A memory allocation failed.

Remarks

The following code shows the variable declarations and calling syntax for this method. Note that this code activates an ITask interface for an existing task named "Test Task".

  ITask *pITask;
  LPCWSTR lpcwszTaskName;
  lpcwszTaskName = L"Test Task";
  hr = pITS->Activate(lpcwszTaskName,
                      IID_ITask,
                      (IUnknown**) &pITask);
For a complete example of | See
Using Activate when you create a new trigger for a task | Creating a New Trigger
Using Activate when you retrieve task properties | Retrieving Task Property Examples
Using Activate when you set task properties | Setting Task Property Examples

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITask, ITaskScheduler


ITaskScheduler::AddWorkItem

The AddWorkItem method adds a task to the schedule of tasks.

HRESULT AddWorkItem(
  LPCWSTR pwszTaskName,
  IScheduledWorkItem *pWorkItem
);

Parameters

pwszTaskName
[in] String that specifies the name of the task to add. The task name must conform to Windows NT/Windows 2000 file-naming conventions but cannot include backslashes, because nesting within the task folder object is not allowed.
pWorkItem
[out] Pointer that receives the requested interface.

Return Values

The AddWorkItem method returns one of the following values.

Value | Description
S_OK | The operation was successful.
ERROR_FILE_EXISTS | A task with the specified name already exists. The actual return value is HRESULT_FROM_WIN32(ERROR_FILE_EXISTS).
E_INVALIDARG | One or more of the arguments is not valid.
E_OUTOFMEMORY | Not enough memory is available to complete the operation.

Remarks

Task scheduler provides two methods for adding work items: NewWorkItem and AddWorkItem. Of these methods, each has its specific advantage. AddWorkItem prevents naming collisions, but also requires two disk write operations per call. One write operation is performed when the call to AddWorkItem creates an empty work item object on the disk, followed by another write operation when IPersistFile::Save is called.

NewWorkItem does not prevent naming collisions, but requires only one disk write operation when IPersistFile::Save is called. Although NewWorkItem is more efficient with respect to disk write operations, the application runs the risk of having another application create a work item with the same name before the call to IPersistFile::Save is made.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem, ITaskScheduler, ITaskScheduler::NewWorkItem


ITaskScheduler::Delete

The Delete method deletes a task.

HRESULT Delete(
  LPCWSTR pwszName
);

Parameters

pwszName
[in] String that specifies the name of the task to delete.

Return Values

The Delete method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITaskScheduler


ITaskScheduler::Enum

The Enum method retrieves a pointer to an OLE enumerator object that enumerates the tasks in the current task folder.

HRESULT Enum(
  IEnumWorkItems **ppEnumTasks
);

Parameters

ppEnumTasks
[out] Pointer to a pointer to an IEnumWorkItems interface. This interface contains the enumeration context of the current task(s).

Return Values

The Enum method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

By default, the current folder resides on the local computer. For remote computers, call ITaskScheduler::GetTargetComputer and use the name returned by this call. To change the target computer call ITaskScheduler::SetTargetComputer.

The following code shows the variable declarations and calling syntax for this method.

  IEnumWorkItems *pIEnum;
  hr = pITS->Enum(&pIEnum);
For a complete example of | See
Using Enum to retrieve the task names on the local computer | Enumerating Tasks Example

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IEnumWorkItems, ITaskScheduler, ITaskScheduler::GetTargetComputer, ITaskScheduler::SetTargetComputer


ITaskScheduler::GetTargetComputer

The GetTargetComputer method returns the name of the computer on which ITaskScheduler is currently targeted.

HRESULT GetTargetComputer(
  LPWSTR *ppwszComputer
);

Parameters

ppwszComputer
[out] Pointer to a string that contains the name of the target computer for the current task. This string is allocated by the application that invokes GetTargetComputer, and must also be freed using CoTaskMemFree.

Return Values

The GetTargetComputer method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITaskScheduler


ITaskScheduler::IsOfType

The IsOfType method checks the object's type to verify that it supports a particular interface.

HRESULT IsOfType(
  LPCWSTR pwszName,
  REFIID riid
);

Parameters

pwszName
[in] String containing the name of the object to check.
riid
[in] The reference identifier of the interface to be matched.

Return Values

The IsOfType method returns S_OK if the object named by pwszName supports the interface specified in riid, or S_FALSE otherwise.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITaskScheduler


ITaskScheduler::NewWorkItem

The NewWorkItem method creates a new work item, allocating space for the work item and retrieving its address.

HRESULT NewWorkItem(
  LPCWSTR pwszTaskName,
  REFCLSID rclsid,
  REFIID riid,
  IUnknown **ppunk
);

Parameters

pwszTaskName
[in] String that specifies the name of the new work item. This name must conform to Windows NT/Windows 2000 file-naming conventions but cannot include backslashes, because nesting within the task folder object is not allowed.
rclsid
[in] Class identifier of the work item to be created. The only class supported at this time, the task class, has the identifier CLSID_Ctask.
riid
[in] The reference identifier of the interface being requested. The only interface supported at this time, ITask, has the identifier IID_ITask.
ppunk
[out] Pointer to an interface pointer that receives the requested interface. See Remarks for saving the work item to disk.

Return Values

The NewWorkItem method returns one of the following values.

Value | Description
S_OK | The operation was successful.
ERROR_FILE_EXISTS | A work item with the specified name already exists. The actual return value is HRESULT_FROM_WIN32 (ERROR_FILE_EXISTS).
E_INVALIDARG | One or more of the arguments is not valid.
E_OUTOFMEMORY | Not enough memory is available to complete the operation.

Remarks

This method handles memory allocation automatically when creating the new work item.

To save the work item to disk, call IPersistFile::Save . This COM interface is supported by all work item interfaces (currently ITask is the only supported work item interface).

Task scheduler provides two methods for adding work items: NewWorkItem and AddWorkItem. Of these methods, each has its specific advantage. AddWorkItem prevents naming collisions, but also requires two disk write operations per call. One write operation is performed when the call to AddWorkItem creates an empty work item object on the disk, followed by another write operation when IPersistFile::Save is called.

NewWorkItem does not prevent naming collisions, but requires only one disk write operation when IPersistFile::Save is called. Although NewWorkItem is more efficient with respect to disk write operations, the application runs the risk of having another application create a work item with the same name before the call to IPersistFile::Save is made.

The following code shows the declaration and calling syntax for this method.

  LPCWSTR pwszTaskName;
  ITask *pITask;
  pwszTaskName = L"Test Task";

  hr = pITS->NewWorkItem(pwszTaskName,
                         CLSID_CTask,
                         IID_ITask,
                         (IUnknown**)&pITask);
For a complete example of | See
Creating a new task | Creating a Task Using NewWorkItem Example

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IPersistFile::Save, ITask, ITaskScheduler, ITaskScheduler::AddWorkItem


ITaskScheduler::SetTargetComputer

The SetTargetComputer method selects the computer that the ITaskScheduler interface operates on, allowing remote task management and enumeration.

HRESULT SetTargetComputer(
  LPCWSTR pwszComputer
);

Parameters

pwszComputer
[in] String that specifies the target computer for the current instance of the ITaskScheduler interface. To indicate the local computer; set this value to NULL or to the local computer's Universal Naming Convention (UNC) name

Return Values

The SetTargetComputer method returns one of the following values.

Value | Description
S_OK | The method was successful.
SCHED_E_SERVICE_NOT_INSTALLED | The Task Scheduler service is not installed on the target computer.
E_INVALIDARG | The pwszComputer parameter is not valid.
E_OUTOFMEMORY | A memory allocation failure occurred.

Remarks

The current user on the remote computer must have administrative access to use this method. For more information on remote installation requirements, refer to Mstask.hlp.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITaskScheduler


ITaskTrigger

The ITaskTrigger interface is used to access and set triggers for a task. Triggers specify task start times, repetition criteria, and other parameters that control when a task is run.

ITaskTrigger is the primary interface of the task_trigger object. To create a trigger object, call CreateTrigger or GetTrigger.

ITaskTrigger provides the following methods, listed here in vtable order.

Method | Description
SetTrigger | Sets the task trigger values.
GetTrigger | Retrieves the current task trigger.
GetTriggerString | Retrieves the current task trigger in the form of a string.

For information on | See
How the Task Scheduler interfaces work together | The Task Scheduler API

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.


ITaskTrigger::GetTrigger

The GetTrigger method retrieves the current task trigger.

HRESULT GetTrigger(
  PTASK_TRIGGER pTrigger
);

Parameters

pTrigger
[out] Pointer to a TASK_TRIGGER structure that contains the current task trigger. You must set the cbTriggerSize member of the TASK_TRIGGER structure to the size of the task trigger structure before passing the structure to this method.

Return Values

The GetTrigger method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The pTrigger parameter is not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

A scheduled work item can have one or more triggers defined. The times that the work item will run are the union of all the triggers defined for that item.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITaskTrigger, ITaskTrigger::SetTrigger, TASK_TRIGGER


ITaskTrigger::GetTriggerString

The GetTriggerString method retrieves the current task trigger in the form of a string. This string appears in the Task Scheduler user interface in a form similar to "At 2PM every day, starting 5/11/97."

HRESULT GetTriggerString(
  LPWSTR *ppwszTrigger
);

Parameters

ppwszTrigger
[out] Pointer to a string describing the current task trigger. The method that invokes GetTriggerString is responsible for freeing this string using the CoTaskMemFree function.

Return Values

The GetTriggerString method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

ITaskTrigger, ITaskTrigger::GetTrigger, ITaskTrigger::SetTrigger


ITaskTrigger::SetTrigger

The SetTrigger method sets the trigger criteria for a task trigger.

HRESULT SetTrigger(
  const PTASK_TRIGGER pTrigger
);

Parameters

pTrigger
[in] Pointer to a TASK_TRIGGER structure containing the values that define the new task trigger.

Return Values

The SetTrigger method returns one of the following values.

Value | Description
S_OK | The operation was successful.
E_INVALIDARG | The arguments are not valid.
E_OUTOFMEMORY | Not enough memory is available.

Remarks

The wBeginDay, wBeginMonth, and wBeginYear members of the TASK_TRIGGER structure must be set to a valid day, month, and year respectively.

A task can have any number of triggers associated with it. The times that the task will run are the union of all the triggers defined for that task.

To update the task with these new trigger settings, applications must call the IPersistFile::Save method after calling SetTrigger.

The following code shows the variable declaration and calling syntax for this method, including the required members of TASK_TRIGGER.

  TASK_TRIGGER pTrigger;
  ZeroMemory(&pTrigger, sizeof (TASK_TRIGGER));
  pTrigger.wBeginDay =1;
  pTrigger.wBeginMonth =1;
  pTrigger.wBeginYear =1999;

  hr = pITaskTrigger->SetTrigger(&pTrigger);
  pITaskTrigger->Release
For a complete example of | See
Setting the trigger criteria when creating a new trigger | Creating a New Trigger

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IPersistFile::Save, ITaskTrigger, ITaskTrigger::GetTrigger, TASK_TRIGGER


Task Scheduler Structures and Unions

This section describes the Task Scheduler structures and unions.

Name | Description
DAILY | Defines the interval, in days, between invocations of a task.
MONTHLYDATE | Defines the day of the month the task will run.
MONTHLYDOW | Defines the date(s) that the task runs by month, week, and day of the week.
TASK_TRIGGER | Defines the times to run a scheduled work item.
TRIGGER_TYPE_UNION | Defines the invocation schedule of the trigger.
WEEKLY | Defines the interval, in weeks, between invocations of a task.


DAILY

The DAILY structure defines the interval, in days, at which a task is run. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the Type member of the TASK_TRIGGER structure definition.

typedef struct _DAILY {
  WORD DaysInterval;
} DAILY;

Members

DaysInterval
Specifies the number of days between task runs.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

TASK_TRIGGER, TRIGGER_TYPE_UNION


MONTHLYDATE

The MONTHLYDATE structure defines the day of the month the task will run. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the Type member of the TASK_TRIGGER structure definition.

typedef struct _MONTHLYDATE {
  DWORD rgfDays;
  WORD rgfMonths;
} MONTHLYDATE;

Members

rgfDays
Specifies the day of the month a task runs. This value is a bit field that specifies the day(s) the task will run. Bit 0 corresponds to the first of the month, bit 1 to the second, and so forth.
rgfMonths
Specifies the month(s) when the task runs. This value is a combination of the following flags. See Remarks for an example of setting multiple flags.
Flag | Meaning
TASK_JANUARY | The task will run in January.
TASK_FEBRUARY | The task will run in February.
TASK_MARCH | The task will run in March.
TASK_APRIL | The task will run in April.
TASK_MAY | The task will run in May.
TASK_JUNE | The task will run in June.
TASK_JULY | The task will run in July.
TASK_AUGUST | The task will run in August.
TASK_SEPTEMBER | The task will run in September.
TASK_OCTOBER | The task will run in October.
TASK_NOVEMBER | The task will run in November.
TASK_DECEMBER | The task will run in December.

Remarks

The following code fragment provides an example of how you can combine these flags. This example runs a task quarterly.

MONTHLYDATE example;
example.rgfDays = 1;
example.rgfMonths = TASK_JANUARY | TASK_APRIL | TASK_JULY | TASK_OCTOBER;

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

TASK_TRIGGER, TRIGGER_TYPE_UNION


MONTHLYDOW

The MONTHLYDOW (monthly, day of the week) structure defines the date(s) that the task runs by month, week, and day of the week. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the Type member of the TASK_TRIGGER structure definition.

typedef struct _MONTHLYDOW {
  WORD wWhichWeek;
  WORD rgfDaysOfTheWeek;
  WORD rgfMonths;
} MONTHLYDOW;

Members

wWhichWeek
Specifies the week of the month when the task runs. This value is exclusive and is one of the following flags.
Flag | Meaning
TASK_FIRST_WEEK | The task will run between the first and seventh day of the month.
TASK_SECOND_WEEK | The task will run between the eighth and 14th day of the month.
TASK_THIRD_WEEK | The task will run between the 15th and 21st day of the month.
TASK_FOURTH_WEEK | The task will run between the 22nd and 28th of the month.
TASK_LAST_WEEK | The task will run between the last seven days of the month.

rgfDaysOfTheWeek
Specifies the day(s) of the week (specified in wWhichWeek) when the task runs. This value is a combination of the following flags.
Flag | Meaning
TASK_SUNDAY | The task will run on Sunday.
TASK_MONDAY | The task will run on Monday.
TASK_TUESDAY | The task will run on Tuesday.
TASK_WEDNESDAY | The task will run on Wednesday.
TASK_THURSDAY | The task will run on Thursday.
TASK_FRIDAY | The task will run on Friday.
TASK_SATURDAY | The task will run on Saturday.

rgfMonths
Value that describes the month(s) when the task runs. This value is a combination of the following flags.
Flag | Meaning
TASK_JANUARY | The task will run in January.
TASK_FEBRUARY | The task will run in February.
TASK_MARCH | The task will run in March.
TASK_APRIL | The task will run in April.
TASK_MAY | The task will run in May.
TASK_JUNE | The task will run in June.
TASK_JULY | The task will run in July.
TASK_AUGUST | The task will run in August.
TASK_SEPTEMBER | The task will run in September.
TASK_OCTOBER | The task will run in October.
TASK_NOVEMBER | The task will run in November.
TASK_DECEMBER | The task will run in December.

The following code fragment provides an example of how you can combine these flags. This example runs a task on Monday and Friday of the third week of every third month.

MONTHLYDOW example;
example.wWhichWeek = TASK_THIRD_WEEK;
example.rgfDaysOfTheWeek = TASK_FRIDAY | TASK_MONDAY;
example.rgfMonths = TASK_JANUARY | TASK_APRIL | TASK_JULY | TASK_OCTOBER;

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

TASK_TRIGGER, TRIGGER_TYPE_UNION


TASK_TRIGGER

The TASK_TRIGGER structure defines the times to run a scheduled work item. These times may include the start time, end time, duration, and modification flags for the work item. Note that when setting a trigger, the beginning day month and year must be set.

Note A scheduled work item can have one or more triggers defined. The times that the work item will run is the union of all the triggers defined for that item.

typedef struct _TASK_TRIGGER {
  WORD cbTriggerSize;
  WORD Reserved1;
  WORD wBeginYear;
  WORD wBeginMonth;
  WORD wBeginDay;
  WORD wEndYear;
  WORD wEndMonth;
  WORD wEndDay;
  WORD wStartHour;
  WORD wStartMinute;
  DWORD MinutesDuration;
  DWORD MinutesInterval;
  DWORD rgFlags;
  TASK_TRIGGER_TYPE TriggerType;
  TRIGGER_TYPE_UNION Type;
  WORD Reserved2;
  WORD wRandomMinutesInterval;
} TASK_TRIGGER, * PTASK_TRIGGER;

Members

cbTriggerSize
Size of this structure, in bytes.
Reserved1
For internal use only; this value must be zero.
wBeginYear
Year that the task trigger activates. This value must be four digits (1997, not 97). The beginning year must be specified when setting a task.
wBeginMonth
Month of the year (specified in the wBeginYear member) that the task trigger activates. The beginning month must be specified when setting a task.
wBeginDay
Day of the month (specified in the wBeginMonth member) that the task trigger activates. The beginning day must be specified when setting a task.
wEndYear
Year that the task trigger deactivates. This value must be four digits (1997, not 97).
wEndMonth
Month of the year (specified in the wEndYear member) that the task trigger deactivates.
wEndDay
Day of the month (specified in the wEndMonth member) that the task trigger deactivates.
wStartHour
Hour of the day the task runs. This value is on a 24-hour clock; hours go from 00 to 23.
wStartMinute
Minute of the hour (specified in the wStartHour member) that the task runs.
MinutesDuration
Number of minutes after the task starts that the trigger will remain active. The number of minutes specified here must greater than or equal to the MinutesInterval setting.

For example, if you start a task at 8:00 A.M. and want to repeatedly start the task until 5:00 P.M., there would be 540 minutes in the duration.

MinutesInterval
Number of minutes between consecutive task executions. This number is counted from the start of the previous task. The number of minutes specified here must be less than or equal to the MinutesDuration setting.

For example, to run a task every hour from 8:00 A.M. to 5:00 P.M., set this field to 60.

rgFlags
Value that describes the behavior of the trigger. This value is a combination of the following flags.
TASK_TRIGGER_FLAG_HAS_END_DATE
Trigger structure's end date is valid. If this flag is not set, the end date data is ignored and the trigger will be valid indefinitely.
TASK_TRIGGER_FLAG_KILL_AT_DURATION_END
Task will be terminated at the end of the active trigger's lifetime. At the duration end, the Task Scheduler sends a WM_CLOSE message to the associated application. If WM_CLOSE cannot be sent (for example, the application has no windows) or the application has not exited within three minutes of the receiving WM_CLOSE, the Task Scheduler terminates the application using TerminateProcess.
TASK_TRIGGER_FLAG_DISABLED
Task trigger is inactive.
TriggerType
A TASK_TRIGGER_TYPE enumerated value that specifies the type of trigger. This member is used with Type. The type of trigger specified here determines which fields of the TRIGGER_TYPE_UNION specified in Type member will be used. Trigger type is based on when the trigger will run the task.
Type
A TRIGGER_TYPE_UNION structure that specifies details about the trigger. Note that the TriggerType member determines which fields of the TRIGGER_TYPE_UNION union will be used.
Reserved2
For internal use only; this value must be zero.
wRandomMinutesInterval
Not currently used.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem::CreateTrigger, ITaskTrigger::GetTrigger, ITaskTrigger::SetTrigger, TASK_TRIGGER_TYPE , TRIGGER_TYPE_UNION


TRIGGER_TYPE_UNION

The TRIGGER_TYPE_UNION union defines the invocation schedule of the trigger within the Type member of a TASK_TRIGGER structure.

Note that which fields of the TRIGGER_TYPE_UNION union are used by your application depends on the TriggerType member of the TASK_TRIGGER structure.

typedef union _TRIGGER_TYPE_UNION {
  DAILY Daily;
  WEEKLY Weekly;
  MONTHLYDATE MonthlyDate;
  MONTHLYDOW MonthlyDOW;
} TRIGGER_TYPE_UNION;

Members

Daily
A DAILY structure that specifies the number of days between invocation of a task.
Weekly
A WEEKLY structure that specifies the number of weeks between invocations of a task, and day(s) of the week the task will run.
MonthlyDate
A MONTHLYDATE structure that specifies the month(s) and day(s) of the month a task will run.
MonthlyDOW
A MONTHLYDOW structure that specifies the day(s) of the year a task runs by month(s), week of month, and day(s) of week.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

DAILY, MONTHLYDATE, MONTHLYDOW, TASK_TRIGGER, WEEKLY


WEEKLY

The WEEKLY structure defines the interval, in weeks, between invocations of a task. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the Type member of the TASK_TRIGGER structure definition.

typedef struct _WEEKLY {
  WORD WeeksInterval;
  WORD rgfDaysOfTheWeek;
} WEEKLY;

Members

WeeksInterval
Number of weeks between invocations of a task.
rgfDaysOfTheWeek
Value that describes the days of the week the task runs. This value is a bit field and is a combination of the following flags. See Remarks for an example of specifying multiple flags.
Flag | Meaning
TASK_SUNDAY | The task will run on Sunday.
TASK_MONDAY | The task will run on Monday.
TASK_TUESDAY | The task will run on Tuesday.
TASK_WEDNESDAY | The task will run on Wednesday.
TASK_THURSDAY | The task will run on Thursday.
TASK_FRIDAY | The task will run on Friday.
TASK_SATURDAY | The task will run on Saturday.

Remarks

The following code fragment provides an example of how you can combine the rgfDaysOfTheWeek flags. This example runs a task on every other Sunday, Wednesday, and Friday.

WEEKLY example;
example.WeeksInterval = 2;
example.rgfDaysOfTheWeek = TASK_SUNDAY | TASK_WEDNESDAY | TASK_FRIDAY;

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

TASK_TRIGGER, TRIGGER_TYPE_UNION


Task Scheduler Enumerated Types

This section describes the Task Scheduler enumerated types.

Name | Description
TASK_TRIGGER_TYPE | Used to specify the type of trigger for a task.
TASKPAGE | Used to specify the task page to be retrieved.


TASK_TRIGGER_TYPE

The TASK_TRIGGER_TYPE enumerated type defines the types of triggers associated with the task. It is used in the TriggerType member of the TASK_TRIGGER structure.

typedef enum _TASK_TRIGGER_TYPE {
  TASK_TIME_TRIGGER_ONCE            = 0,
  TASK_TIME_TRIGGER_DAILY           = 1,
  TASK_TIME_TRIGGER_WEEKLY          = 2,
  TASK_TIME_TRIGGER_MONTHLYDATE     = 3,
  TASK_TIME_TRIGGER_MONTHLYDOW      = 4,
  TASK_EVENT_TRIGGER_ON_IDLE        = 5,
  TASK_EVENT_TRIGGER_AT_SYSTEMSTART = 6,
  TASK_EVENT_TRIGGER_AT_LOGON       = 7
} TASK_TRIGGER_TYPE, *PTASK_TRIGGER_TYPE;

Members

TASK_TIME_TRIGGER_ONCE
Trigger is set to run the task a single time.

When this value is specified, the Type member of the TASK_TRIGGER structure is ignored.

TASK_TIME_TRIGGER_DAILY
Trigger is set to run the task on a daily interval.

When this value is specified, the DAILY member of the TRIGGER_TYPE_UNION structure is used.

TASK_TIME_TRIGGER_WEEKLY
Trigger is set to run the work item on specific days of a specific week of a specific month.

When this value is specified, the WEEKLY member of the TRIGGER_TYPE_UNION structure is used.

TASK_TIME_TRIGGER_MONTHLYDATE
Trigger is set to run the task on a specific day(s) of the month.

When this value is specified, the MONTHLYDATE member of the TRIGGER_TYPE_UNION structure is used.

TASK_TIME_TRIGGER_MONTHLYDOW
Trigger is set to run the task on specific days, weeks, and months.

When this value is specified, the MONTHLYDOW member of the TRIGGER_TYPE_UNION structure is used.

TASK_EVENT_TRIGGER_ON_IDLE
Trigger is set to run the task if the system remains idle for the amount of time specified by the idle wait time of the task.

When this value is specified, the wStartHour, wStartMinute, and Type member of the TASK_TRIGGER structure are ignored.

TASK_EVENT_TRIGGER_AT_SYSTEMSTART
Trigger is set to run the task at system startup.

When this value is specified, the Type member of the TASK_TRIGGER structure is ignored.

TASK_EVENT_TRIGGER_AT_LOGON
Trigger is set to run the task when a user logs on.

When this value is specified, the Type member of the TASK_TRIGGER structure is ignored.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IScheduledWorkItem::SetIdleWait, TASK_TRIGGER, TRIGGER_TYPE_UNION


TASKPAGE

The TASKPAGE enumerated type defines the property page to be returned .These values are used in the tpType parameter of the IProvideTaskPage::GetPage function.

Each property page can be used to define the properties of a task object.

typedef enum  _TASKPAGE{
  TASKPAGE_TASK     = 0,
  TASKPAGE_SCHEDULE = 1,
  TASKPAGE_SETTINGS = 2
  }TASKPAGE;

Members

TASKPAGE_TASK
Specifies the Task page for the task. This page provides the following UI elements:
  • Run: This field specifies the name of the application associated with the task.
  • This property can also be set programmatically by calling ITask::SetApplicationName.
  • Start in: This field specifies the working directory for the task.
  • This property can also be set programmatically by calling ITask::SetWorkingDirectory.
  • Comments: This field specifies any application-defined comments for the task.
  • This property can also be set programmatically by calling IScheduledWorkItem::SetComment.
  • Run as: (Windows NT/Windows 2000 only.) This field specifies the account name under which the task will run. To the right of this field is a Password button for specifying the password for the account.
  • This property can also be set programmatically by calling IScheduledWorkItem::SetAccountInformation.
  • Enabled (scheduled task runs at specific time): This checkbox specifies whether the TASK_TRIGGER_FLAG_DISABLED flag is set.
  • This property can also be set by setting this flag in the rgFlags member of the TASK_TRIGGER structure.
TASKPAGE_SCHEDULE
Specifies the Schedule page for the task. This page is used to manage the triggers for the task. The user can create triggers, edit triggers, and delete triggers from this page.

This page provides the following UI elements:

  • Trigger list box: This list box is displayed only if multiple triggers exist.
  • Schedule Task: This field specifies how often the task will run: daily, weekly, monthly, once, at system startup, at logon, or when idle.
  • Start Time: This field specifies the time of day the task will run.
  • Advanced: This button allows you to set the start date and end date for running the task.
  • Schedule Task group box: This group box is only displayed if the Scheduled Task field specifies daily, weekly, monthly, or once.
  • Show multiple schedules: Shows all triggers. When checked, Trigger list box is displayed.
TASKPAGE_SETTINGS
Specifies the Settings page for the task. The user can specify what happens when the task is completed, idle conditions, and power management properties for the task.

This page provides the following UI elements:

  • Scheduled Task Completed group box: This group box includes check boxes for setting the TASK_FLAG_DELETE_WHEN_DONE flag and the maximum run time for the task.
  • The TASK_FLAG_DELETE_WHEN_DONE flag can also be set programmatically by calling IScheduledWorkItem::SetFlags. The maximum run time can be set by calling ITask::SetMaxRunTime.
  • Idle Time group box: This group box includes fields for setting idle conditions.
  • The idle time can also be set programmatically by calling IScheduledWorkItem::SetIdleWait. The TASK_FLAG_START_ONLY_IF_IDLE and TASK_FLAG_KILL_ON_IDLE_END flags can be set by calling IScheduledWorkItem::SetFlags.
  • Power management group box: (Windows 95 only) This group box includes check boxes for indicating how the task behaves when the system is loosing power.
  • These properties can also be set programmatically by setting the TASK_FLAG_DONT_START_IF_ON_BATTERIES and TASK_FLAG_KILL_IF_GOING_ON_BATTERIES flags using IScheduledWorkItem::SetFlags.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later (or Windows NT 4.0 with Internet Explorer 4.0 or later).
Windows 95/98/Me: Requires Windows 98/Me (or Windows 95 with Internet Explorer 4.0 or later).
Header: Declared in Mstask.h.

See Also

IProvideTaskPage::GetPage, IScheduledWorkItem::SetAccountInformation, IScheduledWorkItem::SetComment, IScheduledWorkItem::SetFlags, IScheduledWorkItem::SetIdleWait, ITask::SetApplicationName, ITask::SetMaxRunTime, ITask::SetWorkingDirectory, TASK_TRIGGER


Task Scheduler Glossary

E

enumeration objects
An object that provides methods for enumerating tasks in the Scheduled Tasks folder. This object supports two interfaces: IUnknown and IEnumWorkItems.

Enumeration objects are created by calls to ITaskScheduler::Enum.


I

idle conditions
A period of time in which there is no user input on the computer. Idle conditions are associated with the scheduled start time for the task.

These conditions are set by calling IScheduledWorkItem::SetFlags.

idle triggers
An event-based trigger that is fired when the computer becomes idle for a specific amount of time.

Idle triggers are created by setting the TASK_TRIGGER_TYPE member of the TASK_TRIGGER structure to TASK_EVENT_TRIGGER_ON_IDLE.

idle wait time
The time interval (in minutes) used by an idle trigger or idle condition. Idle triggers are event based triggers that are not associated with a scheduled time. Idle conditions are associated with the scheduled start time for the task.

The idle time is set by a call to IScheduledWorkItem::SetIdleWait.


P

priority level
A task setting that determines the frequency and length of the time slices for a process. Priority levels apply only to Windows NT/Windows 2000 and have no effect in Windows 95.

A task can be set to one of the following values.

REALTIME_PRIORITY_CLASS

HIGH_PRIORITY_CLASS

NORMAL_PRIORITY_CLASS

IDLE_PRIORITY_CLASS


S

Scheduled Tasks folder
A folder created by the Task Scheduler service that contains all the tasks scheduled to run on the computer.

To see this folder in Windows 2000, click Start on your Windows 2000 desktop, point to Settings, click Control Panel, and then double-click Scheduled Tasks.


T

task objects
Instances of an object that provides methods for managing tasks. This includes methods for setting and retrieving properties; running, terminating, and deleting tasks; and creating new and retrieving old triggers.

The task object is created by calls to IScheduledWorkItem::CreateTrigger and IScheduledWorkItem::GetTrigger.

task scheduler objects
Instances of an object the represents the Task Scheduler service. This object supports two interfaces: IUnknown and ITaskScheduler (currently tasks are the only type of work items supported by the Task Scheduler service).

Task scheduler objects are created by calls to CoCreateInstance.

task trigger objects
Instances of an object the provides methods for setting and retrieving task triggers. This object supports two interfaces: IUnknown and ITaskTrigger.

Task trigger objects are created by calls to IScheduledWorkItem::CreateTrigger and IScheduledWorkItem::GetTrigger.

See also: triggers.

tasks
Any item that the Task Scheduler can execute. These items may include any of the following (as supported by the operating system on which the task will execute): Win32® applications, Win16 applications, OS/2 applications, MS-DOS® applications, batch files (*.bat), command files (*.cmd), or any properly registered file type.
Tasks folder
The folder that lists all task files (currently, tasks are the only work items available). These files contain the information about the task. The name of these files reflects the name of the task.

You can retrieve the location of the Tasks folder from the registry by getting data for the following value:

HKEY_LOCAL_MACHINE

SOFTWARE

Microsoft

SchedulingAgent

TasksFolder

triggers
A set of criteria that, when met, will cause a task to be executed. Task Scheduler provides time-based and event-based triggers that can specify task start times, repetition criteria, and other parameters.
trigger strings
A string that describes the trigger. This string is created by the Task Scheduler service, and appears in the Task Scheduler user interface in a form similar to "At 2PM every day, starting 5/11/97."
trigger structures
The TASK_TRIGGER structure used when setting or retrieving the criteria that defines the trigger. The criteria includes when the trigger will fire, and the type of the trigger.


W

work items
An item that can be scheduled using the Task Scheduler service. It can be any item that the Task Scheduler service runs at a time specified by the item's trigger(s).

Currently tasks are the only valid type of work item.

working directory
The directory where Task Scheduler will start to run the task. If no working directory is specified, Task Scheduler will run the task in the directory in which the Task Scheduler service executable, Mstask.exe, resides.


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.